1. 程式人生 > >Python paramiko ssh執行shell 報錯Cannot find a Java JDK

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'

 

解決方法:

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

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