Python paramiko ssh执行shell 报错Cannot find a Java JDK

Python编程使用paramiko模块的ssh远程linux执行shell报错

“Cannot find a Java JDK. Please set either set JAVA or put java (>=1.5) in your PATH.”

具体代码如下:

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect(ip,port,username,password)

stdin, stdout, stderr = ssh.exec_command ('/root/jetty-8.1.21/bin/jetty.sh  start')

print("结果:"+str(stdout.read()))

运行结果:

结果:b'Cannot find a Java JDK. Please set either set JAVA or put java (>=1.5) in your PATH.\n'

扫描二维码关注公众号,回复: 4558446 查看本文章

解决方法:

stdin, stdout, stderr = ssh.exec_command ('source /etc/profile;/root/commands/stop_jetty.sh')

source /etc/profile 为使JAVA环境变量生效 以此类推其他环境变量生效。

有的环境变量配置在用户.bash_profile文件里,请根据实际情况修改。

额 。。。后来发现编译环境变量会对已经运行的应用可能有影响,而且执行shell脚本时间较长,还是下面伪终端的方式比较好。

test.sh在linux上是可以单独执行成功的,而且linux上jdk是配置的,一直找不到原因。后来从网上看到exec_command的解释

exec_command参数使用只需要执行一次的命令,因为执行完该命令以后,shell会自动回到ssh初始连接的shell状态下。。。

怀疑是类似于jetty.sh这种多命令的shell文件不能用exec_command去执行

然后修改实现方式,通过创建伪终端的方式实现:

chan = ssh.invoke_shell() #创建一个交互式的shell终端

chan.send('sh /root/commands/stop_task.sh') #利用send函数发送命令,'\n'做回车来执行shell命令。telnet的换行符是\r\n
chan.send('\n')
buff = ''
# m = 0
while not buff.endswith('# '):
    resp = chan.recv(9999).decode()
    buff +=resp
    # m += 1
    # print(m)

result  = buff
print(result)

后来到paramiko的官网查找exec_command信息,应该是要设置exec_command函数中的environment参数来指定对应的命令所需的环境变量。只能先mark下,不知道应该怎么设置。

http://www.paramiko.org/changelog.html?highlight=exec_command

********************************************************天道酬勤************************************************************

猜你喜欢

转载自blog.csdn.net/qq_30599553/article/details/85051210