2016-03-15 47 views
11

只需使用我的第一个paramiko脚本,我们有一个opengear控制台服务器,所以我试图自动安装任何我们插入它的设备。Paramiko - ssh到控制台服务器,必须返回脚本以继续

开放式设备侦听端口上的ssh连接,例如端口1中的设备为3001.我连接到端口8上的设备,该设备工作正常,我的脚本运行,但由于某种原因, “建立交互式SSH会话”消息,我需要在会话中返回以使其运行(所以我有一个ssh会话并且该脚本也是如此,它共享)。

它只是在那里等待,直到我打回来,我试过发送退货,因为你可以看到,但他们不工作,只有手动返回工程,这很奇怪,因为从技术上说他们是同样的事情?

import paramiko 
import time 

def disable_paging(remote_conn): 
    '''Disable paging on a Cisco router''' 
    remote_conn.send("terminal length 0\n") 
    time.sleep(1) 
    # Clear the buffer on the screen 
    output = remote_conn.recv(1000) 
    return output 

if __name__ == '__main__': 
    # VARIABLES THAT NEED CHANGED 
    ip = '192.168.1.10' 
    username = 'root' 
    password = 'XXXXXX' 
    port = 3008 

    # Create instance of SSHClient object 
    remote_conn_pre = paramiko.SSHClient() 

    # Automatically add untrusted hosts (make sure okay for security policy in your environment) 
    remote_conn_pre.set_missing_host_key_policy(
     paramiko.AutoAddPolicy()) 

    # initiate SSH connection 
    remote_conn_pre.connect(ip, username=username, password=password,port=port, look_for_keys=False, allow_agent=False) 
    print "SSH connection established to %s" % ip 

    # Use invoke_shell to establish an 'interactive session' 
    remote_conn = remote_conn_pre.invoke_shell() 
    print "Interactive SSH session established" 
    time.sleep(1) 
    remote_conn.send("\n") 

    # Strip the initial router prompt 
    #output = remote_conn.recv(1000) 

    # See what we have 
    #print output 

    # Turn off paging 
    #disable_paging(remote_conn) 

    # clear any config sessions 
    is_global = remote_conn.recv(1024) 
    if ")#" in is_global: 
     remote_conn.send("end\n") 
     time.sleep(2) 
    # if not in enable mode go to enable mode 
    is_enable = remote_conn.recv(1024) 
    if ">" in is_enable: 
     remote_conn.send("enable\n") 
     time.sleep(1) 
    remote_conn.send("conf t\n") 
    remote_conn.send("int g0/0/1\n") 
    remote_conn.send("ip address 192.168.1.21 255.255.255.0\n") 
    remote_conn.send("no shut\n") 
    remote_conn.send("end\n") 
    # Wait for the command to complete 
    time.sleep(2) 
    remote_conn.send("ping 192.168.1.1\n") 
    time.sleep(1) 

    output = remote_conn.recv(5000) 
    print output 

回答

-1

我发现了另一个模块(netmiko),它正是我想要的,并执行所有这些检查。因为当其他人已经做得更好时,我自己放弃了尝试去做。

使用Netmiko! :)

0

先发送一些命令的“ls -ltr \ n”,然后调用sleep

remote_conn.send("ls -ltr\n") 
time.sleep(1) 
-1

尝试在调试器中运行你的命令,并找出哪些线正在等待输入。如果您只是\ n,您也可以尝试发送\ r或\ r \ n。请记住,输入密钥确实是^ M

您也可以尝试开启详细记录。

import logging 
# ... 
logging.getLogger("paramiko").setLevel(logging.DEBUG) 
+0

日志未定义。我需要添加一些东西吗?还发现第一个carrige返回工作,我看着控制台并看到它,然后它暂停,直到我再次返回脚本然后运行 – AlexW

+0

我添加了导入语句。 –

+0

记录器“paramiko.transport”找不到处理程序 – AlexW

0

我尝试这样做,看到

is_global = remote_conn.recv(1024) 

挂起, 确定 '192.168.1.10' 发送到接收财产以后? 尝试设置超时

remote_conn.settimeout(3) 

3秒例如,该行之后做到这一点:

remote_conn = remote_conn_pre.invoke_shell() 

这种方式的recv FUNC不会挂起,并继续当超时

对我的作品

相关问题