Python利用Pexpect模擬ssh交互

Paste_Image.png

==關(guān)于Pexpect==
Pexpect 是 Don Libes 的 Expect 語言的一個 Python 實現(xiàn),是一個用來啟動子程序,并使用正則表達式對程序輸出做出特定響應(yīng),以此實現(xiàn)與其自動交互的 Python 模塊。 Pexpect 的使用范圍很廣,可以用來實現(xiàn)與 ssh、ftp 、telnet 等程序的自動交互;可以用來自動復(fù)制軟件安裝包并在不同機器自動安裝;還可以用來實現(xiàn)軟件測試中與命令行交互的自動化。

本文利用到的Pexpect的類和方法
  1. spawn()類:
class spawn:
    def __init__(self,command,args=[],timeout=30,maxread=2000,\
    searchwindowsize=None, logfile=None, cwd=None, env=None)

spawn是Pexpect模塊主要的類,用以實現(xiàn)啟動子程序,它有豐富的方法與子程序交互從而實現(xiàn)用戶對子程序的控制。它主要使用 pty.fork() 生成子進程,并調(diào)用 exec() 系列函數(shù)執(zhí)行 command 參數(shù)的內(nèi)容。

  1. spawn()類中的expect()函數(shù):
expect(self, pattern, timeout=-1, searchwindowsize=None)

在參數(shù)中: pattern 可以是正則表達式, pexpect.EOF , pexpect.TIMEOUT ,或者由這些元素組成的列表。需要注意的是,當 pattern 的類型是一個列表時,且子程序輸出結(jié)果中不止一個被匹配成功,則匹配返回的結(jié)果是緩沖區(qū)中最先出現(xiàn)的那個元素,或者是列表中最左邊的元素。使用 timeout 可以指定等待結(jié)果的超時時間 ,該時間以秒為單位。當超過預(yù)訂時間時, expect 匹配到pexpect.TIMEOUT。

  1. spawn()類中的beforeafter屬性:

expect 不斷從讀入緩沖區(qū)中匹配目標正則表達式,當匹配結(jié)束時 pexpect 的 before 成員中保存了緩沖區(qū)中匹配成功處之前的內(nèi)容, pexpect 的 after 成員保存的是緩沖區(qū)中與目標正則表達式相匹配的內(nèi)容。

child = pexpect.spawn('/bin/ls /') 
child.expect (pexpect.EOF) 
print child.before

以上代碼就是打印在根目錄下面執(zhí)行l(wèi)s命令后的輸出內(nèi)容

  1. spawn()類中的send系列函數(shù):
send(self, s) 
sendline(self, s='') 
sendcontrol(self, char)

這些方法用來向子程序發(fā)送命令,模擬輸入命令的行為。 與 send() 不同的是 sendline() 會額外輸入一個回車符 ,更加適合用來模擬對子程序進行輸入命令的操作。 當需要模擬發(fā)送 “Ctrl+c” 的行為時,還可以使用 sendcontrol() 發(fā)送控制字符。

child.sendcontrol('c')

功能模塊分解
  1. 首先我們需要一個可以單獨的session會話,可以由connect函數(shù)創(chuàng)建指定host,username和password的會話子進程
PROMPT = ['#','$','>','\$','>>>']
def createChildSession(host,username,password):
    command = 'ssh '+username+'@'+host
    child = pexpect.spawn(command)
    ret = child.expect([pexpect.TIMEOUT,'Are you sure you want to continue connecting','[P|p]assword']+PROMPT)
    if ret == 0:
        print('[-] Error Connecting')
        return
    if ret == 1:
        child.sendline('yes')
        ret = child.expect([pexpect.TIMEOUT,'[p|P]assword'])
        if ret == 0:
            print('[-] Error Connecting')
            return
        if ret == 1:
            send_command(password)
            return
    if ret == 2:
        send_command(password)
        return
    return child

利用spawn創(chuàng)建會話之后,利用expect匹配可能存在的返回結(jié)果,如果匹配'Are you sure you want to continue connecting' 說明需要確認認證信息,如果直接返回password或者Password這里利用[p|P]assword正則來匹配,說明需要輸入密碼,如果直接是PROMPT中存在的字符,說明直接登錄上去了。

  1. 一個單獨的執(zhí)行命令的函數(shù):
def send_command(child,cmd):
    child.sendline(cmd)
    child.expect(PROMPT)
    print(child.before)

一旦通過驗證,我們就可以用上面的command函數(shù)在ssh會話中發(fā)送命令,然后等待命令提示符的出現(xiàn),最后將命令的執(zhí)行結(jié)果通過child.before打印出來。

  1. 一個包含參數(shù)解析的main函數(shù):
def main():
    parse = optparse.OptionParser('Usage %prog -H <host> -u <username> -p <password> -c <command>')
    parse.add_option('-H',dest='host',type='string',help='specify the host')
    parse.add_option('-u',dest='username',type='string',help='specify the username')
    parse.add_option('-p',dest='password',type='string',help='specify the password')    
    parse.add_option('-c',dest='command',type='string',help='specify the command')

    (options,args)=parse.parse_args()
    host = options.host
    username = options.username
    password = options.password
    command = options.command
    
    session = createChildSession(host,username,password)
    send_command(session,command)

optparse是一個用來給你的代碼添加各種命令參數(shù)的庫,用其解析出輸入的host,username,password已經(jīng)command,然后調(diào)用創(chuàng)建session會話,最后利用send_command向此session發(fā)送命令

tianxianggendeiMac:Python-Study Apple$ python ssh.py -H pi.****.com -u root -p ***** -c pwd

輸出:

 pwd
/root
root@raspberrypi:~
完整代碼
#!/usr/bin/python
#-*-coding:utf-8-*-
# date:2016-6-21
# author:root
# 利用pexpect模擬ssh登陸

import pexpect
import optparse

PROMPT = ['#','$','>','\$','>>>']

def send_command(child,cmd):
    child.sendline(cmd)
    child.expect(PROMPT)
    print(child.before)

def createChildSession(host,username,password):
    command = 'ssh '+username+'@'+host
    child = pexpect.spawn(command)
    ret = child.expect([pexpect.TIMEOUT,'Are you sure you want to continue connecting','[P|p]assword']+PROMPT)
    if ret == 0:
        print('[-] Error Connecting')
        return
    if ret == 1:
        child.sendline('yes')
        ret = child.expect([pexpect.TIMEOUT,'[p|P]assword'])
        if ret == 0:
            print('[-] Error Connecting')
            return
        if ret == 1:
            send_command(password)
            return
    if ret == 2:
        send_command(password)
        return
    return child

def main():
    parse = optparse.OptionParser('Usage %prog -H <host> -u <username> -p <password> -c <command>')
    parse.add_option('-H',dest='host',type='string',help='specify the host')
    parse.add_option('-u',dest='username',type='string',help='specify the username')
    parse.add_option('-p',dest='password',type='string',help='specify the password')    
    parse.add_option('-c',dest='command',type='string',help='specify the command')

    (options,args)=parse.parse_args()
    host = options.host
    username = options.username
    password = options.password
    command = options.command
    
    session = createChildSession(host,username,password)
    send_command(session,command)

if __name__ == '__main__':
    main()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容