paramiko的ssh与vsftp示例

2023-10-14 15:48
文章标签 示例 ssh paramiko vsftp

本文主要是介绍paramiko的ssh与vsftp示例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

我已验证的示例:

 

def paramiko_ssh():host = "123.56.14.5"port = 22client = paramiko.SSHClient()client.load_system_host_keys()client.set_missing_host_key_policy(paramiko.client.WarningPolicy())try:client.connect(host, port, username='root', password='xxx', timeout=30)except Exception as e:print(e)stdin, stdout, stderr = client.exec_command('ls /opt')for line in stdout:print('... ' + line.strip('\n'))client.close()def paramiko_key():try:k = paramiko.RSAKey.from_private_key_file("~/.ssh/id_rsa")client = paramiko.SSHClient()client.set_missing_host_key_policy(paramiko.AutoAddPolicy())client.connect(hostname="123.56.14.5", username="root", pkey=k)stdin, stdout, stderr = client.exec_command('ls /opt')for line in stdout:print('... ' + line.strip('\n'))except Exception as e:print(e)finally:client.close()

 

pexpect代码示例     

#!/usr/bin/python
# encoding=utf-8
# Filename: pexpect_test.py
import pexpect
defsshCmd(ip, passwd, cmd):ret = -1ssh = pexpect.spawn('ssh root@%s "%s"' % (ip, cmd))try:i = ssh.expect(['password:', 'continue connecting(yes/no)?'], timeout=5)if i == 0:ssh.sendline(passwd)elif i == 1:ssh.sendline('yes\n')ssh.expect('password:')ssh.sendline(passwd)ssh.sendline(cmd)r = ssh.read()print rret = 0except pexpect.EOF:print "EOF"ret = -1except pexpect.TIMEOUT:print "TIMEOUT"ret = -2finally:ssh.close()return retsshCmd('xxx.xxx.xxx.xxx','xxxxxx','ls /root')

paramiko代码示例

注意:必须要增加client.load_system_host_keys()此句,否则报如下错误:

unbound method missing_host_key() must be called with AutoAddPolicy instance as first argument (got SSHClient instance instead)

#!/usr/bin/python
# encoding=utf-8
# Filename: paramiko_test.py
import datetime
import threading
import paramikodefsshCmd(ip, username, passwd, cmds):try:client = paramiko.SSHClient()client.load_system_host_keys()client.set_missing_host_key_policy(paramiko.AutoAddPolicy)client.connect(ip, 22, username, passwd, timeout=5)for cmd in cmds:stdin, stdout, stderr = client.exec_command(cmd)lines = stdout.readlines()# print outfor line in lines:print line,print '%s\t 运行完毕\r\n' % (ip)except Exception, e:print '%s\t 运行失败,失败原因\r\n%s' % (ip, e)finally:client.close()#上传文件       
defuploadFile(ip,username,passwd):try:t=paramiko.Transport((ip,22))t.connect(username=username,password=passwd)sftp=paramiko.SFTPClient.from_transport(t)remotepath='/root/main.py'localpath='/home/data/javawork/pythontest/src/main.py'sftp.put(localpath,remotepath)print '上传文件成功'except Exception, e:print '%s\t 运行失败,失败原因\r\n%s' % (ip, e)finally:t.close()#下载文件 
defdownloadFile(ip,username,passwd):try:t=paramiko.Transport((ip,22))t.connect(username=username,password=passwd)sftp=paramiko.SFTPClient.from_transport(t)remotepath='/root/storm-0.9.0.1.zip'localpath='/home/data/javawork/pythontest/storm.zip'sftp.get(remotepath,localpath)print '下载文件成功'except Exception, e:print '%s\t 运行失败,失败原因\r\n%s' % (ip, e)finally:t.close()  if __name__ == '__main__':# 需要执行的命令列表cmds = ['ls /root', 'ifconfig']# 需要进行远程监控的服务器列表servers = ['xxx.xxx.xxx.xxx']username = "root"passwd = "xxxxxx"threads = []print "程序开始运行%s" % datetime.datetime.now()# 每一台服务器创建一个线程处理for server in servers:th = threading.Thread(target=sshCmd, args=(server, username, passwd, cmds))th.start()threads.append(th)# 等待线程运行完毕for th in threads:th.join()print "程序结束运行%s" % datetime.datetime.now()#测试文件的上传与下载uploadFile(servers[0],username,passwd)downloadFile(servers[0],username,passwd)

 

Secure File Transfer Using SFTPClient

SFTPClient is used to open an sftp session across an open ssh Transport and do remote file operations.

An SSH Transport attaches to a stream (usually a socket), negotiates an encrypted session, authenticates, and then creates stream tunnels, called Channels, across the session. Multiple channels can be multiplexed across a single session (and often are, in the case of port forwardings).

 

以下是用密码认证功能登录的

#!/usr/bin/env python

import paramiko

 

socks=('127.0.0.1',22)

testssh=paramiko.Transport(socks)

testssh.connect(username='root',password='000000')

sftptest=paramiko.SFTPClient.from_transport(testssh)

remotepath="/tmp/a.log"

localpath="/tmp/c.log"

sftptest.put(remotepath,localpath)

sftptest.close()

testssh.close()

 

以下是用DSA认证登录的(PubkeyAuthentication)
#!/usr/bin/env python

import paramiko

 

serverHost = "192.168.1.172"

serverPort = 22

userName = "root"

keyFile = "/root/.ssh/zhuzhengjun"

known_host = "/root/.ssh/known_hosts"

channel = paramiko.SSHClient();

#host_keys = channel.load_system_host_keys(known_host)

channel.set_missing_host_key_policy(paramiko.AutoAddPolicy())

channel.connect(serverHost, serverPort,username=userName, key_filename=keyFile )

testssh=paramiko.Transport((serverHost,serverPort))

mykey = paramiko.DSSKey.from_private_key_file(keyFile,password='xyxyxy')

testssh.connect(username=userName,pkey=mykey)

sftptest=paramiko.SFTPClient.from_transport(testssh)

filepath='/tmp/e.log'

localpath='/tmp/a.log'

sftptest.put(localpath,filepath)

sftptest.close()

testssh.close()

 

以下是用RSA Key认证登录的

#!/usr/bin/evn python

 

import os

import paramiko

 

host='127.0.0.1'

port=22

testssh=paramiko.Transport((host,port))

privatekeyfile = os.path.expanduser('~/.ssh/badboy')

mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile,password='000000')

username = 'root'

testssh.connect(username=username, pkey=mykey)

sftptest=paramiko.SFTPClient.from_transport(testssh)

filepath='/tmp/e.log'

localpath='/tmp/a.log'

sftptest.put(localpath,filepath)

sftptest.close()

testssh.close()

 

另一种方法:

 

在paramiko中使用用户名和密码通过sftp传输文件,不使用key文件。

import getpass

import select

import socket

import traceback

import paramiko

def putfile():

    #import interactive

    # setup logging

    paramiko.util.log_to_file('demo.log')

    username = username

    hostname = hostname

    port = 22

    # now connect

    try:

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        sock.connect((hostname, port))

    except Exception, e:

        print '*** Connect failed: ' + str(e)

        traceback.print_exc()

        sys.exit(1)

    t = paramiko.Transport(sock)

    try:

        t.start_client()

    except paramiko.SSHException:

        print '*** SSH negotiation failed.'

        sys.exit(1)

    keys = {}

    # check server's host key -- this is important.

    key = t.get_remote_server_key()

    # get username

    t.auth_password(username, password)

    sftp = paramiko.SFTPClient.from_transport(t)

    # dirlist on remote host

    d=datetime.date.today()-datetime.timedelta(1)

    sftp.put(localFile,serverFile)

         sftp.close()

    t.close()

 

使用DSA认证登录的(PubkeyAuthentication)

 

#!/usr/bin/env python

 

import socket

import paramiko

import os

 

username='root'

hostname='192.168.1.169'

port = 22

 

sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.connect((hostname, port))

 

t=paramiko.Transport(sock)

t.start_client()

key=t.get_remote_server_key()

#t.auth_password(username,'000000')

privatekeyfile = os.path.expanduser('/root/.ssh/zhuzhengjun')

mykey=paramiko.DSSKey.from_private_key_file(privatekeyfile,password='061128')

t.auth_publickey(username,mykey)

sftp=paramiko.SFTPClient.from_transport(t)

sftp.put("/tmp/a.log","/tmp/h.log")

sftp.close()

t.close()

 

使用RSA Key验证

#!/usr/bin/env python

 

import socket

import paramiko

import os

 

username='root'

hostname='127.0.0.1'

port = 22

 

sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.connect((hostname, port))

 

t=paramiko.Transport(sock)

t.start_client()

key=t.get_remote_server_key()

#t.auth_password(username,'000000')

privatekeyfile = os.path.expanduser('~/.ssh/badboy')

mykey=paramiko.RSAKey.from_private_key_file(privatekeyfile,password='000000')

t.auth_publickey(username,mykey)

sftp=paramiko.SFTPClient.from_transport(t)

sftp.put("/tmp/a.log","/tmp/h.log")

sftp.close()

t.close()

 

这篇关于paramiko的ssh与vsftp示例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/211500

相关文章

SpringBoot线程池配置使用示例详解

《SpringBoot线程池配置使用示例详解》SpringBoot集成@Async注解,支持线程池参数配置(核心数、队列容量、拒绝策略等)及生命周期管理,结合监控与任务装饰器,提升异步处理效率与系统... 目录一、核心特性二、添加依赖三、参数详解四、配置线程池五、应用实践代码说明拒绝策略(Rejected

SQL中如何添加数据(常见方法及示例)

《SQL中如何添加数据(常见方法及示例)》SQL全称为StructuredQueryLanguage,是一种用于管理关系数据库的标准编程语言,下面给大家介绍SQL中如何添加数据,感兴趣的朋友一起看看吧... 目录在mysql中,有多种方法可以添加数据。以下是一些常见的方法及其示例。1. 使用INSERT I

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

MySQL 定时新增分区的实现示例

《MySQL定时新增分区的实现示例》本文主要介绍了通过存储过程和定时任务实现MySQL分区的自动创建,解决大数据量下手动维护的繁琐问题,具有一定的参考价值,感兴趣的可以了解一下... mysql创建好分区之后,有时候会需要自动创建分区。比如,一些表数据量非常大,有些数据是热点数据,按照日期分区MululbU

Python函数作用域示例详解

《Python函数作用域示例详解》本文介绍了Python中的LEGB作用域规则,详细解析了变量查找的四个层级,通过具体代码示例,展示了各层级的变量访问规则和特性,对python函数作用域相关知识感兴趣... 目录一、LEGB 规则二、作用域实例2.1 局部作用域(Local)2.2 闭包作用域(Enclos

C++20管道运算符的实现示例

《C++20管道运算符的实现示例》本文简要介绍C++20管道运算符的使用与实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录标准库的管道运算符使用自己实现类似的管道运算符我们不打算介绍太多,因为它实际属于c++20最为重要的

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

Linux中SSH服务配置的全面指南

《Linux中SSH服务配置的全面指南》作为网络安全工程师,SSH(SecureShell)服务的安全配置是我们日常工作中不可忽视的重要环节,本文将从基础配置到高级安全加固,全面解析SSH服务的各项参... 目录概述基础配置详解端口与监听设置主机密钥配置认证机制强化禁用密码认证禁止root直接登录实现双因素

ModelMapper基本使用和常见场景示例详解

《ModelMapper基本使用和常见场景示例详解》ModelMapper是Java对象映射库,支持自动映射、自定义规则、集合转换及高级配置(如匹配策略、转换器),可集成SpringBoot,减少样板... 目录1. 添加依赖2. 基本用法示例:简单对象映射3. 自定义映射规则4. 集合映射5. 高级配置匹

C++11作用域枚举(Scoped Enums)的实现示例

《C++11作用域枚举(ScopedEnums)的实现示例》枚举类型是一种非常实用的工具,C++11标准引入了作用域枚举,也称为强类型枚举,本文主要介绍了C++11作用域枚举(ScopedEnums... 目录一、引言二、传统枚举类型的局限性2.1 命名空间污染2.2 整型提升问题2.3 类型转换问题三、C