2017-02-14 130 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机器。 ) –