python ssh實現 python實現ssh

2021-10-19 20:19:11 字數 1356 閱讀 5775

首先呢,學習了怎麼修改路由器配置,新增guest

對著敲著玩,就知道應該怎麼弄了

然後是重點,實現ssh連線

各種模板網上是有的,我想要解決的問題是:如何將原來螢幕的訊息儲存到檔案之中

涉及到兩個問題:

1.child.before儲存的是上一次命令所返回的資訊

2.很多命令的輸出資訊在一頁之內顯示不完全,所以呢,需要按幾次空格

試了很多次想了一種這樣的解決方法:

在child.sendline()的時候,就直接把這些空格敲上,反正不會影響到下一次的查詢

然後,就是在新建檔案的時候,記錄上一次的查詢命令

下個版本會把出錯處理加上

沒有使用child.interact()

**分享如下:

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import pexpect

import time

if __name__ == '__main__':

user = ''

ip = ''

mypassword = ''

rootpassword = ''

enter = '\n'

child = pexpect.spawn('ssh -1 '+user+'@'+ip)

fout = file('mylog.txt','w')

child.logfile = fout

child.expect ('password:')

child.sendline (mypassword)

child.expect ('router>')

child.sendline ('en')

child.expect ('password:')

child.sendline (rootpassword)

cmd = ''

while true:

print "route#"

beforecmd = cmd

cmd = raw_input()

child.expect('router#')

child.sendline(cmd)

for i in range(10):

child.send(' ')

if beforecmd != '':

filename = beforecmd.replace(' ','-')+'.txt'

f=open(filename,'w')

f.write(child.before)

if cmd == 'exit':

break

child.sendline('exit')

python ssh登入 python ssh連線

pip install paramiko 檢視並啟動ssh服務 service ssh status 新增使用者 useradd d home zet zet passwd zet 賦予ssh許可權 vi etc ssh sshd config 新增allowusers zet 客戶端 coding...

socketserver實現併發(Python)

server類 處理鏈結 request類 處理通訊 基於tcp 服務端 import socketserver class myserver socketserver.baserequesthandler def handle self print self.request conn print ...

python ssh工具paramiko的一點修改

經常使用paramiko工具對幾百台裝置進行管理。主要是每天到上邊取檔案過來,作為備份。今天發現程式執行了10個小時還沒有結束,就上去看乙個究竟。檢視日誌,發現在取一台伺服器上的檔案時卡在那裡了。自己手動ssh登入上去,執行了乙個ls命令就卡住了,原來是這個伺服器的硬碟出問題了。怪不得取不到檔案。但...