1. 程式人生 > >python pexpect ssh 遠端登入伺服器

python pexpect ssh 遠端登入伺服器

使用了python中的pexpect模組,在測試程式碼之前,可輸入python進入互動介面,輸入help('pexpect'),查詢是否本地含有pexpect模組。

如果沒有,linux系統輸入 easy_install pexpect便可自動安裝。

測試程式碼,連線127.0.0.1

下面是我手動連線127.0.0.1, 發現只有在首次使用ssh連線127.0.0.1時,需要輸入yes or no ,而後再次使用ssh ,則不需要再次輸入yes 

直接輸入密碼即可。


後續測試程式碼是二次連結,無需查詢是否需要輸入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()