python ssh之paramiko模組使用

2022-05-10 03:37:21 字數 2890 閱讀 1385

1.安裝:

sudo pip install paramiko

2.連線到linux伺服器

方法一:

#paramiko.util.log_to_file('ssh.log') #寫日誌檔案

client = paramiko.sshclient()

client.set_missing_host_key_policy(paramiko.autoaddpolicy()) #允許連線不在~/.ssh/known_hosts檔案中的主機

client.connect('ip',22, 'username','password') #指定ip位址,埠,使用者名稱和密碼進行連線

方法二:

transport = paramiko.transport(('ip', port)) #獲取連線

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

ssh = paramiko.sshclient()

ssh._transport = transport

# coding=utf-8

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()

if __name__ == "__main__":

conn = sshconnection('192.168.87.200', 22, 'username', 'password')

localpath = 'hello.txt'

remotepath = '/home/hupeng/workspace/python/test/hello.txt'

print 'downlaod start'

conn.download(remotepath, localpath)

print 'download end'

print 'put begin'

conn.put(localpath, remotepath)

print 'put end'

conn.exec_command('whoami')

conn.exec_command('cd workspace/python/test;pwd') #cd需要特別處理

conn.exec_command('pwd')

conn.exec_command('tree workspace/python/test')

conn.exec_command('ls -l')

conn.exec_command('echo "hello python" > python.txt')

conn.exec_command('ls hello') #顯示錯誤資訊

conn.close()

python ssh登入 python ssh連線

pip install paramiko 檢視並啟動ssh服務 service ssh status 新增使用者 useradd d home zet zet passwd zet 賦予ssh許可權 vi etc ssh sshd config 新增allowusers zet 客戶端 coding...

python ssh工具paramiko的一點修改

經常使用paramiko工具對幾百台裝置進行管理。主要是每天到上邊取檔案過來,作為備份。今天發現程式執行了10個小時還沒有結束,就上去看乙個究竟。檢視日誌,發現在取一台伺服器上的檔案時卡在那裡了。自己手動ssh登入上去,執行了乙個ls命令就卡住了,原來是這個伺服器的硬碟出問題了。怪不得取不到檔案。但...

python SSH連線工具類

import os import paramiko class sshconnectionutils hostname port 22 username password ssh def init self,hostname,port,username,password self.hostname ...