ssh远程连接linux服务器并执行命令

时间:2019-06-12
本文章向大家介绍ssh远程连接linux服务器并执行命令,主要包括ssh远程连接linux服务器并执行命令使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

详细方法:

SSHClient中的方法 参数和参数说明
connect(实现ssh连接和校验)

hostname:目标主机地址

port:主机端口

username:校验的用户名

password:登录密码

pkey:私钥方式身份验证

key_filename:用于私钥身份验证的文件名

timeout:连接超时设置

allow_agent:这是布尔型,设置False的时候禁止使用ssh代理

look_for_keys:也是布尔型,禁止在.ssh下面找私钥文件

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。

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






原文地址:https://www.cnblogs.com/liuage/p/11011594.html