ssh remote connection linux server and execute the command

 

Details Methods:

 

 

 

SSHClient Methods Parameters and parameter description
connect (connection ssh implement and check)

hostname: the destination host address

port: host port

username: user name check

password: password

pkey: private key authentication mode

key_filename: file name for the private key authentication

timeout: connection timeout setting

allow_agent: It is Boolean, set False prohibit the use ssh agent

look_for_keys: Boolean also prohibit the private key file to find the following in .ssh

compress: Set the compression

exec_command (remote execution of commands)

stdin, stdout, stderr: these are the three standard input, output, or error, is used to obtain the results of command execution, parameters and the method is not

command: Run string with double quotes.

bufsize: File buffer size, default is 1

load_system_host_keys (load local public key file) filename: Specifies the remote host's public key log file
set_missing_host_key_policy (remote host does not have the key)

AutoAddPolicy: automatically add the host name and host key to the local HostKeys objects

RejectPolicy: automatically reject unknown host name and key (default)

WarningPolicy: accepting unknown host, but there will be a warning

paramiko core components SFTPClient class that implements the remote file operations, such as upload, download, privilege, status.

Class method SFTPClient Parameters and parameter description
from_transport (SFTP by using a client has been communicating passage)

localpath: path to the local file

remotepath: remote path

callback: Get the total number of bytes transmitted and received bytes

confirm: whether to call stat () method after the file is uploaded, the file size is determined

get (downloaded from the SFTP server files to the local)

 remotepath: the need to download a file path

localpath: save a local file path

And put in as: callback

os method

mkdir: Resume directory

remove: Delete

rename: 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。

 
连接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

参考资料:https://www.cnblogs.com/qianyuliang/p/6433250.html






Guess you like

Origin www.cnblogs.com/liuage/p/11011594.html