ssh遠程鏈接linux服務器並執行命令

 

詳細方法:html

 

 

 

SSHClient中的方法 參數和參數說明
connect(實現ssh鏈接和校驗)

hostname:目標主機地址python

port:主機端口linux

username:校驗的用戶名shell

password:登陸密碼服務器

pkey:私鑰方式身份驗證session

key_filename:用於私鑰身份驗證的文件名ssh

timeout:鏈接超時設置ui

allow_agent:這是布爾型,設置False的時候禁止使用ssh代理this

look_for_keys:也是布爾型,禁止在.ssh下面找私鑰文件spa

compress:設置壓縮

exec_command(遠程執行命令)

stdin,stdout,stderr:這三個分別是標準輸入、輸出、錯誤,用來獲取命令執行結果,並不算方法的參數

command:執行命令的字符串,帶雙引號。

bufsize:文件緩衝大小,默認爲1

load_system_host_keys(加載本地的公鑰文件) filename:指定遠程主機的公鑰記錄文件
set_missing_host_key_policy(遠程主機沒有密鑰)

AutoAddPolicy:自動添加主機名和主機密鑰到本地的HostKeys對象

RejectPolicy:自動拒絕未知的主機名和密鑰(默認)

WarningPolicy:接受未知主機,可是會有警告

paramiko的核心組件SFTPClient類 實現遠程文件的操做,好比上傳、下載、權限、狀態等。

SFTPClient類的方法 參數和參數說明
from_transport(使用一個已經經過已經連通的SFTP客戶端通道)

localpath:本地文件的路徑

remotepath:遠程路徑

callback:獲取已接收的字節數和總傳輸的字節數

confirm:文件上傳完畢後是否調用stat()方法,肯定文件大小

get(從SFTP服務器上下載文件到本地)

 remotepath:需下載的文件路徑

localpath:保存本地的文件路徑

callback:和put的同樣

os方法

mkdir:簡歷目錄

remove:刪除

rename:重命名

stat:獲取遠程文件信息

listdir:獲取指定目錄列表

   

shell通道鏈接:invoke_shell的用法

invoke_shell(*args, **kwds)

 

Request an interactive shell session on this channel. If the server allows it, the channel will then be directly connected to the stdin, stdout, and stderr of the shell.

 

Normally you would call get_pty before this, in which case the shell will operate through the pty, and the channel will be connected to the stdin and stdout of the pty.

 

When the shell exits, the channel will be closed and can’t be reused. You must open a new channel if you wish to open another shell.

 

在這個通道請求一個交互式的shell會話,若是服務容許,這個通道將會直接鏈接標準輸入、標準輸入和錯誤的shell,一般咱們會在使用它以前調用get_pty的用法,這樣shell會話是經過僞終端處理的,而且會話鏈接標準輸入和輸出,當咱們shell退出的時候,這個通道也會關閉,而且能再次使用,你必修從新開另外一個shell。

 

Python 使用paramiko.Transport SSH方式登陸路由器執行命令

import paramiko

t = paramiko.Transport(('x.x.x.x',22))   # 設置SSH鏈接的遠程主機地址和端口
t.connect(username='xxx',password='xxx')   # 設置登錄用戶名和密碼等參數
chan=t.open_session()   # 鏈接成功後打開一個channel
chan.settimeout(15)     # 設置會話超時時間
chan.get_pty()          # 打開遠程的terminal
chan.invoke_shell()     # 激活terminal
chan.send("display current-configuration\n")
chan.send(" "*60)
time.sleep(5)   # 若是程序執行的太快,沒有等到返回足夠的信息,chan.recv(65535)不能獲得想要的結果
# 使用一些條件循環,判斷何時讀取返回結果,實際常常報錯啊!
# str.chan.recv(65535)
# while not str.endswith('#'):
#     str=chan.recv(65535)    #recv_buffer=65535
f = open("D:\\t.txt","w")
f.write(chan.recv(65535).decode('ascii'))
f.close()
t.close()
---------------------
做者:m20
來源:CSDN
原文:https://blog.csdn.net/u010306071/article/details/79080697
版權聲明:本文爲博主原創文章,轉載請附上博文連接!

 
鏈接linux服務器

import paramiko


ip = "192.168.55.55"
port = 22
username = 'root'
password = '23561314'

# 建立SSH對象
ssh = paramiko.SSHClient()
# 容許鏈接不在known_hosts文件上的主機
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 鏈接服務器
ssh.connect(hostname=ip, port=22, username=username, password=password)
# 執行命令
print (u'鏈接%s成功' % ip)
stdin, stdout, stderr = ssh.exec_command('pwd;df')

# # 獲取結果
result = stdout.read()

# # 獲取錯誤提示(stdout、stderr只會輸出其中一個)
# err = stderr.read()
# # 關閉鏈接
# ssh.close()
print(result)
# print(stdin, result, err)

SFTPClient上傳下載:

基於用戶名密碼上傳下載:

import paramiko

transport = paramiko.Transport(('hostname',22))
transport.connect(username='wupeiqi',password='123')

sftp = paramiko.SFTPClient.from_transport(transport)
# 將location.py 上傳至服務器 /tmp/test.py
sftp.put('/tmp/location.py', '/tmp/test.py')
# 將remove_path 下載到本地 local_path
sftp.get('remove_path', 'local_path')

transport.close()

基於公鑰密鑰上傳下載:

 

import paramiko

private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')

transport = paramiko.Transport(('hostname', 22))
transport.connect(username='wupeiqi', pkey=private_key )

sftp = paramiko.SFTPClient.from_transport(transport)
# 將location.py 上傳至服務器 /tmp/test.py
sftp.put('/tmp/location.py', '/tmp/test.py')
# 將remove_path 下載到本地 local_path
sftp.get('remove_path', 'local_path')

transport.close()

 

 

封裝上傳下載代碼:

#coding:utf-8
import paramiko
import uuid

class SSHConnection(object):

def __init__(self, host='192.168.2.103', port=22, username='root',pwd='123456'):
self.host = host
self.port = port
self.username = username
self.pwd = pwd
self.__k = None

def connect(self):
transport = paramiko.Transport((self.host,self.port))
transport.connect(username=self.username,password=self.pwd)
self.__transport = transport

def close(self):
self.__transport.close()

def upload(self,local_path,target_path):
# 鏈接,上傳
# file_name = self.create_file()
sftp = paramiko.SFTPClient.from_transport(self.__transport)
# 將location.py 上傳至服務器 /tmp/test.py
sftp.put(local_path, target_path)

def download(self,remote_path,local_path):
sftp = paramiko.SFTPClient.from_transport(self.__transport)
sftp.get(remote_path,local_path)

def cmd(self, command):
ssh = paramiko.SSHClient()
ssh._transport = self.__transport
# 執行命令
stdin, stdout, stderr = ssh.exec_command(command)
# 獲取命令結果
result = stdout.read()
print (str(result,encoding='utf-8'))
return result

ssh = SSHConnection()
ssh.connect()
ssh.cmd("ls")
ssh.upload('s1.py','/tmp/ks77.py')
ssh.download('/tmp/test.py','kkkk',)
ssh.cmd("df")
ssh.close()

 

















































#!/usr/bin/env python
#encoding:utf8
 
import paramiko
 
hostname = '192.168.0.202'
port = 22
username = 'root'
password = 'password'
 
localpath = "D:\Develop\Python\paramiko/\\test_file.txt"  #須要上傳的文件(源)
remotepath = "/data/tmp/test_file.txt"      #遠程路徑(目標)
 
try:
              # 建立一個已經連通的SFTP客戶端通道
              t = paramiko.Transport((hostname, port))
              t.connect(username=username, password=password)
              sftp = paramiko.SFTPClient.from_transport(t)
              
              # 上傳本地文件到規程SFTP服務端
              sftp.put(localpath,remotepath) #上傳文件
              
              # 下載文件
              sftp.get(remotepath,'D:\Develop\Python\paramiko/\\test_down.txt')
              
              # 建立目錄
              # sftp.mkdir('/data/tmp/userdir', 0755)
              
              # 刪除目錄
              # sftp.rmdir('/data/tmp/userdir')
              
              # 文件重命名
              #sftp.rename(remotepath,'/data/tmp/new_file.txt')
              
              # 打印文件信息
              print sftp.stat(remotepath)
              
              # 打印目錄信息
              print sftp.listdir('/data/tmp/')
              
              # 關閉鏈接
              t.close()
              
except Exception, e:
              print str(e)

 






































部分信息轉載於https://www.cnblogs.com/zhang-yulong/p/6540457.html

參考資料:http://www.javashuo.com/article/p-ssvvskes-c.html

https://blog.csdn.net/Sufeiboy/article/details/82078059
相關文章
相關標籤/搜索