2016-11-23 74 views
1

我想在遠程計算機上使用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() 

sample output

任何意見和建議,將不勝感激,謝謝您!

回答

1

幾年前,我遇到過類似的問題,結果可能有幾個原因。

一個可能的選擇是該調用等待獲得shell提示符以返回。但是,對於需要sudo的命令,其行爲可能會發生變化:在某些情況下,它會要求您先輸入密碼。在其他情況下(例如,如果您剛剛使用了sudo且尚未超時),則不需要再次輸入密碼。這種不一致可能會導致問題。

看一看here - 使用-k可能會解決您的問題。

爲了解決這個問題,您必須定義(如果可能)sudo將始終需要密碼,從而使其一致。

另一個可能引發的問題是shell提示的定義(某些shell使用>,其他使用$);對於sudo可能也是如此 - 它可能會打印Password:,其中不包含shell提示符並且可能無法被遠程命令代理識別,並且可能會打印其他內容,例如, password

+0

感謝您的回覆,我嘗試過使用sudo -k,但沒有運氣。有趣的是,當我硬編碼dbname和像[[「」「send_string_and_wait('sh /orashare/ettool/Validation_Final.sh dbname client'+」\ n「,1,True)['」「] – Prince

+0

等客戶端值時, m「在傳遞變量時遇到問題」「send_string_and_wait(」sh /orashare/ettool/Validation_Final.sh「+」「+ str(dbname)+」「+ str(cl)+」\ n「,0,True)」 「」我猜這肯定是語法問題,如果我錯了,請糾正我。 – Prince

+0

試着看看你從遠程服務器上得到了什麼,使用'-k'只能確保遠程服務器的行爲一致。但是,你必須記住,當要求輸入密碼時,它不使用shell符號(比如''''或'$'),因此如果paramiko只等待其中一個,它就會被阻塞。 'Password:'(或者它出現在你的系統中的任何東西)被認爲是該呼叫的shell標記。 – Mike

相關問題