设为首页 加入收藏

TOP

Python之路:堡垒机实例(一)
2017-09-30 17:39:55 】 浏览:10158
Tags:Python 之路 堡垒 实例

堡垒机前戏

开发堡垒机之前,先来学习Python的paramiko模块,该模块机遇SSH用于连接远程服务器并执行相关操作

SSHClient

用于连接远程服务器并执行基本命令

基于用户名密码连接:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import paramiko
  
# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname = 'c1.salt.com' , port = 22 , username = 'wupeiqi' , password = '123' )
  
# 执行命令
stdin, stdout, stderr = ssh.exec_command( 'df' )
# 获取命令结果
result = stdout.read()
  
# 关闭连接
ssh.close()
 1 import paramiko
 2 
 3 transport = paramiko.Transport(('hostname', 22))
 4 transport.connect(username='wupeiqi', password='123')
 5 
 6 ssh = paramiko.SSHClient()
 7 ssh._transport = transport
 8 
 9 stdin, stdout, stderr = ssh.exec_command('df')
10 print stdout.read()
11 
12 transport.close()
SSHClient 封装 Transport

基于公钥密钥连接:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import paramiko
 
private_key = paramiko.RSAKey.from_private_key_file( '/home/auto/.ssh/id_rsa' )
 
# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname = 'c1.salt.com' , port = 22 , username = 'wupeiqi' , key = private_key)
 
# 执行命令
stdin, stdout, stderr = ssh.exec_command( 'df' )
# 获取命令结果
result = stdout.read()
 
# 关闭连接
ssh.close()
 1 import paramiko
 2 
 3 private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')
 4 
 5 transport = paramiko.Transport(('hostname', 22))
 6 transport.connect(username='wupeiqi', pkey=private_key)
 7 
 8 ssh = paramiko.SSHClient()
 9 ssh._transport = transport
10 
11 stdin, stdout, stderr = ssh.exec_command('df')
12 
13 transport.close()
SSHClient 封装 Transport

SFTPClient

用于连接远程服务器并执行上传下载

基于用户名密码上传下载

1
2
3
4
5
6
7
8
9
10
11
12
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()

基于公钥密钥上传下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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()
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import paramiko
 4 import uuid
 5 
 6 clas
首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python-Day4 Python基础进阶之生.. 下一篇简明Python教程自学笔记——命令..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目