在学习堡垒机之前,我们需要首先了解下Python的paramiko模块,该模块机遇SSH用于连接远程服务器并执行相关操作。
SSHClient
用于连接远程服务器并执行基本命令
基于用户名密码连接:
import paramiko # 创建SSH对象 ssh = paramiko.SSHClient() # 允许连接不在know_hosts文件中的主机 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接服务器 ssh.connect(hostname='192.168.132.130', port=22, username='wangxin', password='111111') # 执行命令 stdin, stdout, stderr = ssh.exec_command('df') # 获取命令结果 result = stdout.read() # 关闭连接 ssh.close()
SSHClient 封装 Transport方式
import paramiko transport = paramiko.Transport(('192.168.132.130', 22)) transport.connect(username='wangxin', password='111111') ssh = paramiko.SSHClient() ssh._transport = transport stdin, stdout, stderr = ssh.exec_command('df') print stdout.read() transport.close()
SFTPClient
用于连接远程服务器并执行上传下载
基于用户名密码上传下载
import paramiko transport = paramiko.Transport(('192.168.132.130',22)) transport.connect(username='wangxin',password='111111') 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()
修改haproxy配置文件实例
#!/usr/bin/env python # _*_ coding:utf-8 _*_ __author__ = 'wang' import paramiko import uuid class Haproxy(object): def __init__(self): self.host = '192.168.132.130' self.port = 22 self.username = 'wangxin' self.pwd = '111111' def create_file(self): file_name = str(uuid.uuid4()) #生成随机文件名 with open(file_name,'w') as f: f.write('ares') return file_name def run(self): self.connect() self.upload() self.rename() self.close() 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): #连接上传 file_name = self.create_file() #transport = paramiko.Transport((self.host,self.port)) #transport.connect(username=self.username,password=self.pwd) sftp = paramiko.SFTPClient.from_transport(self.__transport) #将文件上传到服务器 sftp.put(file_name,'/home/wangxin/111.py') #transport.close() def rename(self): # 创建SSH对象 ssh = paramiko.SSHClient() # 允许连接不在know_hosts文件中的主机 #ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接服务器 #ssh.connect(hostname=self.host, port=self.port, username=self.username, password=self.pwd) ssh._transport = self.__transport # 执行命令 stdin, stdout, stderr = ssh.exec_command('mv /home/wangxin/111.py /home/wangxin/333.py') # 获取命令结果 result = stdout.read() print result # 关闭连接 #ssh.close() a = Haproxy() a.run()
堡垒机的实现
堡垒机:即在一个特定的网络环境下,为了保障网络和数据不受来自外部和内部用户的入侵和破坏,而运用各种技术手段实时收集和监控网络环境中每一个组成部分的系统状态、安全事件、网络活动,以便集中报警、记录、分析、处理的一种技术手段。
注:配置.brashrc实现ssh登陆后自动执行脚本,如://home/wangxin/menu.py
用户登录实现:
import getpass user = raw_input('username:') pwd = getpass.getpass('password') if user == 'ares' and pwd == '111111': print '登陆成功' else: print '登陆失败'
根据用户获取相关服务器列表:
dic = { 'ares': [ '192.168.132.130', '192.168.132.131', ], 'wangxin': [ '192.168.132.132', '192.168.132.133', ] } host_list = dic['ares'] print 'please select:' for index, item in enumerate(host_list, 1): print index, item inp = raw_input('your select (No):') inp = int(inp) hostname = host_list[inp-1] port = 22
根据用户名、私钥登陆服务器:
tran = paramiko.Transport((hostname, port,)) tran.start_client() default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa') key = paramiko.RSAKey.from_private_key_file(default_path) tran.auth_publickey('wupeiqi', key) # 打开一个通道 chan = tran.open_session() # 获取一个终端 chan.get_pty() # 激活器 chan.invoke_shell() ######### # 利用sys.stdin,肆意妄为执行操作 # 用户在终端输入内容,并将内容发送至远程服务器 # 远程服务器执行命令,并将结果返回 # 用户终端显示内容 ######### chan.close() tran.close()
数据库基本操作:
建表操作:
create table students ( id int not null auto_increment primary key, name char(8) not null, sex char(4) not null, age tinyint unsigned not null, tel char(13) null default "-" );
Python MySQL API:
(批量)插入数据:
import MySQLdb conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='test') cur = conn.cursor() li =[ ('ares','cn'), ('wangxin,'cn'), ] reCount = cur.executemany('insert into UserInfo(Name,Address) values(%s,%s)',li) conn.commit() cur.close() conn.close() print reCount
删除数据:
import MySQLdb conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='test') cur = conn.cursor() reCount = cur.execute('delete from UserInfo') conn.commit() cur.close() conn.close() print reCount
修改数据:
import MySQLdb conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='test') cur = conn.cursor() reCount = cur.execute('update UserInfo set Name = %s',('aresxin',)) conn.commit() cur.close() conn.close() print reCount
# ############################## fetchone/fetchmany(num) ############################## import MySQLdb conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='test') cur = conn.cursor() reCount = cur.execute('select * from UserInfo') print cur.fetchone() print cur.fetchone() cur.scroll(-1,mode='relative') print cur.fetchone() print cur.fetchone() cur.scroll(0,mode='absolute') print cur.fetchone() print cur.fetchone() cur.close() conn.close() print reCount # ############################## fetchall ############################## import MySQLdb conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='test') #cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor) cur = conn.cursor() reCount = cur.execute('select Name,Address from UserInfo') nRet = cur.fetchall() cur.close() conn.close() print reCount print nRet for i in nRet: print i[0],i[1]
更详细,更NB的信息,请参考:http://www.cnblogs.com/wupeiqi/articles/5095821.html
来源:https://www.cnblogs.com/aresxin/p/5132015.html