python pexpect ssh 遠程登錄服務器的方法
使用了python中的pexpect模塊,在測試代碼之前,可輸入python進入交互界面,輸入help('pexpect'),查詢是否本地含有pexpect模塊。
如果沒有,linux系統(tǒng)輸入 easy_install pexpect便可自動安裝。
測試代碼,連接127.0.0.1
下面是我手動連接127.0.0.1, 發(fā)現(xiàn)只有在首次使用ssh連接127.0.0.1時,需要輸入yes or no ,而后再次使用ssh ,則不需要再次輸入yes
直接輸入密碼即可。
后續(xù)測試代碼是二次鏈接,無需查詢是否需要輸入yes or no
import pexpect def send_command(child, cmd): child.sendline(cmd) child.expect(PROMT) print child.before def connect(user, host, password): ssh_newkey = 'Ary you sure you want to continue connecting' connStr = 'ssh ' + user + '@' + host child = pexpect.spawn(connStr) ''' ret = child.expect([pexpect.TIMEOUT, ssh_newkey]) if ret == 0: print "[-] Error 1" return elif ret == 1: child.sendline('yes') ''' res = child.expect([pexpect.TIMEOUT, '[P|p]assword:']) if res == 0: print "[-] Error 2" return elif res == 1: child.sendline(password) child.expect(PROMT) return child def main(): host = '127.0.0.1'#測試主機ip或者主機名 user = 'root'#測試賬號 password = 'root'#測試密碼 child = connect(user, host, password) send_command(child, 'w') if __name__ == '__main__': main()
可以用pxssh模塊更簡單來完成ssh的連接
from pexpect import pxssh def send_command(s, cmd): s.sendline(cmd) s.prompt() print s.before def connect(host, user, password): try: s = pxssh.pxssh() s.login(host, user, password) return s except: print "error" exit(0) def main(): s = connect('127.0.0.1', 'root', '15110506010') send_command(s, 'whoami') if __name__ == '__main__': main()
批量連接肉雞。
from pexpect import pxssh botnet = [] class client: def __init__(self, user, host, password): self.user=user self.host=host self.password=password self.child=self.connect() def connect(self): try: s = pxssh.pxssh() s.login(self.host, self.user, self.password) return s except Exception, e: print "Error *" + str(e) def send_command(self, cmd): self.child.sendline(cmd) self.child.prompt() return self.child.before def addclient(user, host, password): c = client(user, host, password) botnet.append(c) def botnetcommand(command): for c in botnet: output = c.send_command(command) print "ip: " + str(c.host) print output def main(): addclient('root', '127.0.0.1', 'toor') addclient('root', '****', '*****') botnetcommand('pwd') if __name__=='__main__': main()
以上這篇python pexpect ssh 遠程登錄服務器的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
淺析Python 實現(xiàn)一個自動化翻譯和替換的工具
這篇文章主要介紹了Python 實現(xiàn)一個自動化翻譯和替換的工具,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-04-04?python中pandas讀取csv文件?時如何省去csv.reader()操作指定列步驟
這篇文章主要介紹了?python中pandas讀取csv文件?時如何省去csv.reader()操作指定列步驟,對正在工作的你可能有一定的幫助,需要的朋友可以參考一下2022-01-01Python直接使用plot()函數(shù)畫圖的方法實例
Python非常簡單而又非常強大,它的功能之一就是畫出漂亮的圖表,實現(xiàn)數(shù)據(jù)的可視化,下面這篇文章主要給大家介紹了關于Python直接使用plot()函數(shù)畫圖的相關資料,需要的朋友可以參考下2022-05-05