使用了python中的pexpect模塊,在測(cè)試代碼之前,可輸入python進(jìn)入交互界面,輸入help('pexpect'),查詢是否本地含有pexpect模塊。
如果沒(méi)有,linux系統(tǒng)輸入 easy_install pexpect便可自動(dòng)安裝。
測(cè)試代碼,連接127.0.0.1
下面是我手動(dòng)連接127.0.0.1, 發(fā)現(xiàn)只有在首次使用ssh連接127.0.0.1時(shí),需要輸入yes or no ,而后再次使用ssh ,則不需要再次輸入yes
直接輸入密碼即可。
后續(xù)測(cè)試代碼是二次鏈接,無(wú)需查詢是否需要輸入yes or no
import pexpect def send_command(child, cmd): child.sendline(cmd) child.expect(PROMT) print child.beforedef 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 childdef main(): host = '127.0.0.1'#測(cè)試主機(jī)ip或者主機(jī)名 user = 'root'#測(cè)試賬號(hào) password = 'root'#測(cè)試密碼 child = connect(user, host, password) send_command(child, 'w')if __name__ == '__main__': main()
可以用pxssh模塊更簡(jiǎn)單來(lái)完成ssh的連接
from pexpect import pxsshdef send_command(s, cmd): s.sendline(cmd) s.prompt() print s.beforedef 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 pxsshbotnet = []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.beforedef 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 outputdef main(): addclient('root', '127.0.0.1', 'toor') addclient('root', '****', '*****') botnetcommand('pwd')if __name__=='__main__': main()
以上這篇python pexpect ssh 遠(yuǎn)程登錄服務(wù)器的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持IIS7站長(zhǎng)之家。
新聞熱點(diǎn)
疑難解答
網(wǎng)友關(guān)注