Python paramiko模組的安裝與使用

2021-09-20 19:42:05 字數 4070 閱讀 3761

一、安裝paramiko

1

pip3 install paramiko

二、使用使用者名稱密碼方式遠端執行命令

1

2

3

4

5

6

7

8

importparamiko

ssh=paramiko.sshclient()

ssh.set_missing_host_key_policy(paramiko.autoaddpolicy())# 自動接受遠端伺服器host key

ssh.connect('127.0.0.1',22,'username','password')# 遠端主機ip、埠、使用者名稱、密碼

stdin, stdout, stderr=ssh.exec_command('df -h')# 遠端伺服器要執行的命令

forlineinstdout:

print(line)

ssh.close()# 關閉ssh連線

1

2

3

4

5

6

importparamiko

t=paramiko.transport('127.0.0.1',22)

t.connect(username='username', password='password')

sftp=paramiko.sftpclient.from_transport(t)

sftp.put('local_file','remote_folder')

t.close()

1

2

3

4

5

6

importparamiko

t=paramiko.transport('127.0.0.1',22)

t.connect(username='username', password='password')

sftp=paramiko.sftpclient.from_transport(t)

sftp.get('remote_file','local_folder')

t.close()

四、使用ssh key方式遠端執行命令(前提遠端主機已經接受了你的公鑰)

1

2

3

4

5

6

7

8

9

10

11

importparamiko

private_key_path='/home/***/.ssh/id_rsa'

key=paramiko.rsakey.from_private_key_file(private_key_path)

ssh=paramiko.sshclient()

ssh.set_missing_host_key_policy(paramiko.autoaddpolicy())

ssh.connect('127.0.0.1',22, username='username', pkey=key)

stdin, stdout, stderr=ssh.exec_command('df')

print(stdout.read())

ssh.close()

五、使用scp方式遠端執行命令

1

2

3

4

5

6

7

8

importparamiko

scp=paramiko.transport(('127.0.0.1',22))

scp.connect(username='username', password='password')

channel=scp.open_session()

channel.exec_command('touch hello/test.txt')

channel.close()

scp.close()

daibaiyang119

python paramiko 各種錯誤

這個錯誤出現在伺服器接受連線但是ssh守護程序沒有及時響應的情況 預設是15s 要解決這個問題,需要將paramiko的響應等待時間調長。transport.py中def init 初始化函式中 how long seconds to wait for the ssh banner self.ban...

Python Paramiko模組的使用

windows下有很多非常好的ssh客戶端,比如putty。在python的世界裡,你可以使用原始套接字和一些加密函式建立自己的ssh客戶端或服務端,但如果有現成的模組,為什麼還要自己實現呢。使用paramiko庫中的pycrypto能夠讓你輕鬆使用ssh2協議。paramiko的安裝方法網上有很多...

Python paramiko實現跳轉控制

通過ssh 的proxycommand,建立關係,用paramiko模組,呼叫proxycommand方法 一 通過一台跳板機免密 a主機 b跳板機 c主機 做好a免密登入b,b免密登入c a主機 ssh下新增檔案b private,內容為b的私鑰 a主機 ssh下增加config檔案,內容為 ho...