我的第一个Python随笔
自学Python也很长时间了,注册博客园写了第一篇随笔。之前想过很多次,但是始终不知道该怎么开始,内容如何,现在想想,随笔嘛,是自己的想法,也自己的实践,又是自己的锻炼。话不多说,开始今天的正式内容。
Python的paramiko模块。
paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接。由于使用的是python这样的能够跨平台运行的语言,所以所有python支持的平台,如Linux, Solaris, BSD, MacOS X, Windows等,paramiko都可以支持,因此,如果需要使用SSH从一个平台连接到另外一个平台,进行一系列的操作时,paramiko是最佳工具之一。
SSHClient
用于连接远程服务器并执行基本命令
基于用户名密码连接:
import paramiko # 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='192.168.30.129', port=22, username='sunqi', password='') # 执行命令
stdin, stdout, stderr = ssh.exec_command('df')
# 获取命令结果
result = stdout.read() # 关闭连接
ssh.close()
示例代码:
import paramiko ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh.connect(hostname='192.168.30.129',port=22,username='root',password='')#测试机器为Linux虚拟机(CentOS 7)
while True:
cmd = input('>>:')
stdin,stdout,stderr = ssh.exec_command(cmd)
result = stdout.read()
if stdout:
print(str(result,'utf8'))
else:
print(str(stderr.read(),'utf8')) ssh.close()
SFTPClient
用于连接远程服务器并执行上传:
import paramiko '''
从windows上传文件到Linux虚拟机
IP地址: 192.168.30.129
端口:22
'''
host = '192.168.30.129'
port = 22 t = paramiko.Transport((host,port))
t.connect(username="root",password='',)
sftp = paramiko.SFTPClient.from_transport(t)
target_path = '/var/log/windows.log'
local_path = 'E:\\sunqi.log'
sftp.put(local_path,target_path)
t.close()
最后将多线程和这个paramiko模块综合起来写了一个批量主机管理程序
请看到的朋友原谅我的混乱代码规范,我会加倍努力的!
批量主机管理系统远程连接主机实现命令的执行文件的上传下载:
主机列表:
示例代码:host_dir.py
host_dic = {
'group1':{
'C1':{'host':'192.168.30.129','port':22,'username':'root','password':''},
'C2':{'host':'192.168.30.130','port':22,'username':'root','password':''},
'C3':{'host':'192.168.30.131','port':22,'username':'root','password':''}
},
'group2':{
'C4':{'host':'192.168.30.132','port':22,'username':'root','password':''},
'C5':{'host':'192.168.30.134','port':22,'username':'root','password':''},
'C6':{'host':'192.168.30.135','port':22,'username':'root','password':''},
}
}
运行代码:run_code.py
import threading
import paramiko
import os
from paramiko模块.批量主机管理小项目.host_dir import host_dic '''
主机批量管理程序
实现多个主机的同时管理
利用多线程以及paramiko模块
实现多个主机同时执行命令,上传或下载文件
'''
class host_manage():
def __init__(self,host,port,username,password):
self.host = host
self.port = port
self.username = username
self.password = password
def command(self,cmd):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh.connect(hostname=self.host,port=self.port,username=self.username,password=self.password)
#cmd = input(">>:")
stdin, stdout, stderr = ssh.exec_command(cmd)
result = stdout.read()
if stdout:
print(str(result, 'utf8'))
else:
print(str(stderr.read(), 'utf8')) def upload(self):
t = paramiko.Transport(self.host,self.port)
t.connect(username=self.username,password=self.password)
sftp = paramiko.SFTPClient.from_transport(t)
target_path = '/var/log/windows.log'
local_path = 'E:\\sunqi.log'
sftp.put(local_path,target_path)
t.close()
pass
def download(self):
pass
def choose_group():
print('可管理主机分组')
for k in host_dic:
print(k)
for i in host_dic[k]:
print(host_dic[k][i])
group_num = input('>>:选择主机编号')
return group_num
def run():
num = choose_group()
print('已选组号:%s' %num)
selected = input(">>:输入即将进行的操作:command、upload、download")
if selected =="command":
cmd = input('>>:请输入要批量操作的命令:')
thread_conut = []
for i in host_dic[num]:
func = host_manage(host=host_dic[num][i]['host'],port=host_dic[num][i]['port'],username=host_dic[num][i]['username'],password=host_dic[num][i]['password'])
if hasattr(func,selected):
p = threading.Thread(target=getattr(func,selected),args=(cmd,))
thread_conut.append(p)
p.start()
for i in thread_conut:
i.join() if __name__ == '__main__':
run()
我的第一个Python随笔的更多相关文章
- 第一个python程序
一个python程序的两种执行方式: 1.第一种方式是通过python解释器: cmd->python->进入python解释器->编写python代码->回车. 2.第二种方 ...
- 第一个python实例--监控cpu
#第一个python实例:监控cpu #/bin/bash/env Python from __future__ import print_function from collections impo ...
- 一个python爬虫小程序
起因 深夜忽然想下载一点电子书来扩充一下kindle,就想起来python学得太浅,什么“装饰器”啊.“多线程”啊都没有学到. 想到廖雪峰大神的python教程很经典.很著名.就想找找有木有pdf版的 ...
- Virtualenv: 一个Python环境管理工具(windown版本)
1.安装virtualenv 在安装virtualenv之前,我们需要安装至少有一个版本的python:因为virtualenv是python的一个第三方模块,必须基于python环境才能安装: 如果 ...
- 3.第一个python程序
学习任何一门语言的第一步,首先要写个'hello world',这算是程序员的一个传统.但在写之前,还有注意几个问题. 首先,python是一门脚本语言,而脚本语言的特点就是:我们写的代码会先由解释器 ...
- ipython, 一个 python 的交互式 shell,比默认的python shell 好用得多,支持变量自动补全,自动缩进,支持 bash shell 命令,内置了许多很有用的功能和函数
一个 python 的交互式 shell,比默认的python shell 好用得多,支持变量自动补全,自动缩进,支持 bash shell 命令,内置了许多很有用的功能和函数. 若用的是fish s ...
- 第一个 Python 程序 - Email Manager Demo
看了一些基础的 Python 新手教程后,深深感觉到 Python 的简洁与强大,这是我的第一个 Python Demo.下面是完整代码与执行截图. 代码: # encoding: utf-8 ''' ...
- 【Python脚本】Python创建删除文件-----------我的第一个Python脚本
Python相对C++和Java来说,是解释性语言,非常适合来编写脚本. 很久之前就开始学习Python的语法了,今天写了第一个Python的脚本,来简化我的一些日常工作. 我平时学习的时候喜欢新建一 ...
- Python学习笔记4-如何快速的学会一个Python的模块、方法、关键字
想要快速的学会一个Python的模块和方法,两个函数必须要知道,那就是dir()和help() dir():能够快速的以集合的型式列出该模块下的所有内容(类.常量.方法)例: #--encoding: ...
随机推荐
- C 标准库 - string.h之strcat使用
strcat Appends a copy of the source string to the destination string. The terminating null character ...
- MySQL优化--表之间JOIN的关键字ON和Where (01)
1. Join关键字,就是把多个表连接起来 而on和where都是条件,但是针对的对象不一样 1.1. 关键字 On是指怎样把两个表连接起来,如: on a.name = b.name 是一行一行的比 ...
- 在windows服务器上设置301、伪静态(wordpress)
新建一个httpd.ini文件,插入代码: [ISAPI_Rewrite] RewriteCond Host: ^wuchao\.cc$ RewriteRule (.*) http\://www\.w ...
- 常用工具说明--Maven使用说明
什么是Maven? 如今我们构建一个项目需要用到很多第三方的类库,如写一个使用Spring的Web项目就需要引入大量的jar包.一个项目Jar包的数量之多往往让我们瞠目结舌,并且Jar包之间的关系错综 ...
- Eclipse 工具栏无法移动的解决办法
升级到Juno后发现工具栏有些乱 而且无法拖动,试了下http://blog.csdn.net/cxx504659987/article/details/38532599的方法 发现配置文件里没有文中 ...
- Entity Framework6 with Visual Studio 2013 update3 for Oracle 11g
2014年7月的时候,写了一篇关于EF5 with visual studio 2010 for oracle 11g的博文 原文地址 :http://www.cnblogs.com/HouZhiHo ...
- java 并发(五)---AbstractQueuedSynchronizer(5)
问题 : ArrayBlockQueue 和 LinkedBlockQueue 的区别 两者的实现又是怎么样的 应用场景 BlockingQueue 概述 blockingQueue 是个接口,从名字 ...
- request方法总结
1.获得指定的头 String header = response.getHeader("user-agent"); 2.获得所有头的名称 Enumeration<Stri ...
- Be opinionated out of the box but get out of the way quickly as requirements start to diverge from
Be opinionated out of the box but get out of the way quickly as requirements start to diverge from t ...
- flask 继承模版的基本使用1