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
通常提示以空格結束。也許'endswith('[root @ home /]#')'?或''[root @ home〜]#''。 –
謝謝Girisha。你的建議解決了這個問題。 –
嗨Girisha,我在其他情況下遇到過類似的問題。在命令交互期間,當輸出帶有字符串'你想現在配置網絡嗎? (是/否)[默認是]',腳本需要發送'是'命令。以下是爲此編寫的代碼。 channel.send('yes \ n')未執行。 elif channel_data.endswith('你想現在配置Prime網絡嗎?(是/否)[default yes]'): channel.send('yes \ n') –