python 簡單的人機交互

近來寫腳本,通過svn list命令獲取結果,卻發現在處理返回結果的時候,有時候會報錯,發現是因爲在svn list的時候,Linux系統有這個提示:

ATTENTION!  Your password for authentication realm:

   <https://ch3p-gen-ias-vcs001.ch3.syniverse.com:443> SVN HK Repo

can only be stored to disk unencrypted!  You are advised to configure
your system so that Subversion can store passwords encrypted, if
possible.  See the documentation for details.

You can avoid future appearances of this warning by setting the value
of the 'store-plaintext-passwords' option to either 'yes' or 'no' in
'/root/.subversion/servers'.
-----------------------------------------------------------------------
Store password unencrypted (yes/no)?

要求輸入yes還是no,嘗試了幾種方法,發現可以通過paramiko解決,代碼如下:

import paramiko

#get an paramiko connection
def get_ssh_interact_conn(server_ip, username, passwd):
    #parameter is server ip, username, password

                t = paramiko.Transport((server_ip, 22))

                t.connect(None, username, passwd)

              chan = t.open_session()

               # timeout

               chan.settimeout(30)

               #open remote terminal, 如果要輸入的命令很長比如有2000個字符,那麼久需要設置pty的寬度,否則如果使用默認寬度,可能導致要執行的命令被中間截斷,比如默認寬度是5,而發送的命是“ps -ef | grep welcom”,那麼在發送命令時候就可能變成,“ps -ef \r | grep welcom”,從而導致命令執行失敗

               chan.get_pty(width=2048)

              #activate terminal

              chan.invoke_shell()

              return chan


def get_live_tags_list(svn_list_command):
    # this method can input yes automatically, when encounter 'Store password unencrypted (yes/no)? '
    live_revision_version_list = []
    
    chan = get_ssh_interact_conn('10.202.10.202', 'root', 'root')
   chan.send(svn_list_command + '\n')
    time.sleep(3)
    live_tags_info = chan.recv(2048)
    print live_tags_info
    if 'Store password unencrypted (yes/no)' in live_tags_info:
       print chan.send('yes\n')
        time.sleep(3)
        result = chan.recv(2048)
        print result
      chan.send(svn_list_command + '\n')

                   chan.close()

if name == '__main__':

get_list_tags_list('svn list https://okokok.com/test')

有人推薦expect,我覺得有點麻煩,這個感覺更簡單,有沒有其他更好的方法,也沒有研究過


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章