1. 程式人生 > >python之SSH(互動式和非互動式)

python之SSH(互動式和非互動式)

python中有一個paramiko,功能強大,用來做SSH比較方便

先上程式碼

import paramiko
class SSHConnection(object):
    def __init__(self, host, port, username, password):
        self._host = host
        self._port = port
        self._username = username
        self._password = password
        self._transport = None
        self._sftp = None
        self._client = None
        self._connect()  # 建立連線

    def _connect(self):
        transport = paramiko.Transport((self._host, self._port))
        transport.connect(username=self._username, password=self._password)
        self._transport = transport

    #下載
    def download(self, remotepath, localpath):
        if self._sftp is None:
            self._sftp = paramiko.SFTPClient.from_transport(self._transport)
        self._sftp.get(remotepath, localpath)

    #上傳
    def put(self, localpath, remotepath):
        if self._sftp is None:
            self._sftp = paramiko.SFTPClient.from_transport(self._transport)
        self._sftp.put(localpath, remotepath)

    #執行命令
    def exec_command(self, command):
        if self._client is None:
            self._client = paramiko.SSHClient()
            self._client._transport = self._transport
        stdin, stdout, stderr = self._client.exec_command(command)
        data = stdout.read()
        if len(data) > 0:
            print data.strip()   #列印正確結果
            return data
        err = stderr.read()
        if len(err) > 0:
            print err.strip()    #輸出錯誤結果
            return err

    def close(self):
        if self._transport:
            self._transport.close()
        if self._client:
            self._client.close()

接下來就簡單測試一下exec_command這個命令,比較常用
if __name__ == "__main__":
    conn = SSHConnection('ip', port, 'username', 'password')

    conn.exec_command('ls -ll')
    conn.exec_command('cd /home/test;pwd')  #cd需要特別處理
    conn.exec_command('pwd')
    conn.exec_command('tree /home/test')
exec_command這個函式如果想cd,可以使用pwd這樣可以到當前目錄而不是初始目錄,但是有些情況下,比如chroot,是做不到的,這個時候就需要新的方法

上程式碼

ssh = paramiko.SSHClient() #建立sshclient
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #目的是接受不在本地Known_host檔案下的主機。
    ssh.connect("ip",port,'username','password')
    command='chroot /xxx\n' 
    #conn.write(command)
    chan=ssh.invoke_shell()#新函式
    chan.send(command+'\n')
#\n是執行命令的意思,沒有\n不會執行
 time.sleep(10)#等待執行,這種方式比較慢
#這個時候就可以在chroot目錄下執行命令了
    res=chan.recv(1024)#非必須,接受返回訊息
    chan.close()

注意invoke_shell這個函式即可

另外使用這個函式命令後面記得加“\n”