我想在遠程計算機上使用python-paramiko(在linux2上使用Python 2.7.9)執行sudo命令。 下面是代碼。當我執行的代碼它每次給出不同的輸出,而其工作正常,當我運行在python相同的代碼>>> CMDLINE在需要使用密碼輸入Sudo的遠程服務器上執行命令 - Paramiko
import paramiko
import sys
import time
def send_string_and_wait(command, wait_time, should_print):
shell.send(command)
time.sleep(wait_time)
receive_buffer = shell.recv(1024)
if should_print:
return receive_buffer
dbname='test'
cl='testdb'
host='testhost'
owner='uname'
passwd='p'
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(str(host), username=str(owner), password=str(passwd), port=22)
shell = client.invoke_shell()
send_string_and_wait("sudo su - oracle\n", 1, True)
send_string_and_wait(str(passwd) + "\n", 1, True)
a=send_string_and_wait("sh Validation_Final.sh" + str(' ') + str(dbname) + str(' ') + str(cl) + "\n", 0, True)
print a
client.close()
任何意見和建議,將不勝感激,謝謝您!
感謝您的回覆,我嘗試過使用sudo -k,但沒有運氣。有趣的是,當我硬編碼dbname和像[[「」「send_string_and_wait('sh /orashare/ettool/Validation_Final.sh dbname client'+」\ n「,1,True)['」「] – Prince
等客戶端值時, m「在傳遞變量時遇到問題」「send_string_and_wait(」sh /orashare/ettool/Validation_Final.sh「+」「+ str(dbname)+」「+ str(cl)+」\ n「,0,True)」 「」我猜這肯定是語法問題,如果我錯了,請糾正我。 – Prince
試着看看你從遠程服務器上得到了什麼,使用'-k'只能確保遠程服務器的行爲一致。但是,你必須記住,當要求輸入密碼時,它不使用shell符號(比如''''或'$'),因此如果paramiko只等待其中一個,它就會被阻塞。 'Password:'(或者它出現在你的系統中的任何東西)被認爲是該呼叫的shell標記。 – Mike