2017-02-14 83 views
0
import paramiko 
import time 
import os 


ssh=paramiko.SSHClient() 
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
ssh.connect('server',port=22,username='user',password='pass123') 
print("connected to the linux machine from windows machine.") 

channel=ssh.invoke_shell() 

channel_data = str() 

while True: 
    if channel.recv_ready(): 
     channel_data += channel.recv(9999).decode(encoding='utf_8', errors='strict') 
     os.system('cls') 
     print("##### Device Output #####") 
     print("\n",channel_data) 
     print("\n #####################") 
    else: 
     continue 

    time.sleep(5) 

    if channel_data.endswith('[[email protected] ~]#'): 
     #if block statements are not executed why 
     print("Hi,why not executing this statement") 
     ssh.send('cd /\n') 
     #stdin,stdout,stderr=ssh.exec_command('pwd') 
     #output1=stdout.readlines() 
     print("My present working directory is") 
    elif channel_data.endswith('[[email protected] /]#'): 
     #Also elif block statements are not executed why 
     ssh.send('mkdir BB444') 
     #stdin,stdout,stderr=ssh.exec_command('mkdir /pn444') 
     #output1=stdout.readlines() 
     print("created pn444 directory") 

我使用paramiko進行ssh連接。我能夠登錄到Linux機器。然後我檢查條件,即如果channel_data.endswith('[root @ home〜]#')然後發送「cd /」命令,否則如果channel_data.endswith('[root @ home /]#'),則發送'mkdir BB444 '命令,但是這個腳本沒有發送這些命令。調試後,我看到這些發送命令語句不執行。請讓我知道我在這裏犯了什麼錯誤。Python腳本不發送linux命令。我用Paramiko進行遠程SSH連接

我使用python 3.6,2.1.1的paramiko

+0

通常提示以空格結束。也許'endswith('[root @ home /]#')'?或''[root @ home〜]#''。 –

+0

謝謝Girisha。你的建議解決了這個問題。 –

+0

嗨Girisha,我在其他情況下遇到過類似的問題。在命令交互期間,當輸出帶有字符串'你想現在配置網絡嗎? (是/否)[默認是]',腳本需要發送'是'命令。以下是爲此編寫的代碼。 channel.send('yes \ n')未執行。 elif channel_data.endswith('你想現在配置Prime網絡嗎?(是/否)[default yes]'): channel.send('yes \ n') –

回答

0

的問題可能不是python腳本。在從python腳本發送遠程命令到putty ssh連接時,我遇到了類似的問題。如果您在公司網絡中。一些管理員從參數中刪除命令,例如我用於putty的-m。所以你可以登錄,但是當你嘗試發送一個遠程命令。它沒有到達服務器。如果您在公司網絡上使用有關ssh連接的遠程命令,請諮詢您的管理員。

+0

謝謝Sivaprasath。其實只有企業網絡上的Linux服務器。我將與管理員一起檢查您的建議,但目前我正在發送非常簡單的命令,例如「cd /」或「pwd」或「mkdir pn444」 –

+0

您正在發送遠程命令,這是安全問題,因此不會執行任何命令。還有一件事,如果你使用CISCO服務器或路由器,那麼它的內置安全性就是脫離ssh連接命令的遠程命令。 –

+0

我可以從腳本創建一個文件夾。這意味着我能夠從腳本成功發送命令。以下是代碼。進口的paramiko SSH = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect( '服務器',端口= 22,用戶名= '用戶',口令= 'pass123') 打印( ('創建一個新的目錄是',輸出1(「創建一個新的目錄是',輸出1)」從windows機器連接到Linux機器。 ) –