【发布时间】:2017-02-14 15:08:04
【问题描述】:
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('[root@home ~]#'):
#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('[root@home /]#'):
#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 3.6,paramiko 2.1.1
【问题讨论】:
-
提示符通常以空格结尾。也许
endswith('[root@home /]# ')?或'[root@home ~]# '. -
谢谢 Girisha。您的建议解决了问题。
-
嗨 Girisha,我在其他情况下也遇到了类似的问题。在命令交互期间,当输出带有字符串 'Would you like to configure Network now? (yes/no) [default yes] ',脚本需要发送'yes'命令。下面是为此编写的代码。 channel.send('yes\n') 没有执行。 elif channel_data.endswith('现在要配置 Prime Network 吗?(yes/no) [default yes] '): channel.send('yes\n')
标签: linux ssh paramiko python-3.6