2016-03-15 75 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不會掛起,並繼續當超時

對我的作品

相關問題