Python之路【第八篇】:堡垒机实例以及数据库操作

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()
复制代码
import paramikotransport = paramiko.Transport(('hostname', 22))
transport.connect(username='wupeiqi', password='123')ssh = paramiko.SSHClient()
ssh._transport = transportstdin, stdout, stderr = ssh.exec_command('df')
print stdout.read()transport.close()
复制代码

基于公钥密钥连接:

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()
复制代码
import paramikoprivate_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')transport = paramiko.Transport(('hostname', 22))
transport.connect(username='wupeiqi', pkey=private_key)ssh = paramiko.SSHClient()
ssh._transport = transportstdin, stdout, stderr = ssh.exec_command('df')transport.close()
复制代码

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()
复制代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import paramiko
import uuidclass Haproxy(object):def __init__(self):self.host = '172.16.103.191'self.port = 22self.username = 'wupeiqi'self.pwd = '123'self.__k = Nonedef create_file(self):file_name = str(uuid.uuid4())with open(file_name,'w') as f:f.write('sb')return file_namedef 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 = transportdef close(self):self.__transport.close()def upload(self):# 连接,上传file_name = self.create_file()sftp = paramiko.SFTPClient.from_transport(self.__transport)# 将location.py 上传至服务器 /tmp/test.pysftp.put(file_name, '/home/wupeiqi/tttttttttttt.py')def rename(self):ssh = paramiko.SSHClient()ssh._transport = self.__transport# 执行命令stdin, stdout, stderr = ssh.exec_command('mv /home/wupeiqi/tttttttttttt.py /home/wupeiqi/ooooooooo.py')# 获取命令结果result = stdout.read()ha = Haproxy()
ha.run()
复制代码

堡垒机的实现 

实现思路:

堡垒机执行流程:

  1. 管理员为用户在服务器上创建账号(将公钥放置服务器,或者使用用户名密码)
  2. 用户登陆堡垒机,输入堡垒机用户名密码,现实当前用户管理的服务器列表
  3. 用户选择服务器,并自动登陆
  4. 执行操作并同时将用户操作记录

注:配置.brashrc实现ssh登陆后自动执行脚本,如:/usr/bin/python /home/wupeiqi/menu.py

实现过程

步骤一,实现用户登陆

1
2
3
4
5
6
7
8
import getpass
user = raw_input('username:')
pwd = getpass.getpass('password')
if user == 'alex' and pwd == '123':
    print '登陆成功'
else:
    print '登陆失败'

步骤二,根据用户获取相关服务器列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
dic = {
    'alex': [
        '172.16.103.189',
        'c10.puppet.com',
        'c11.puppet.com',
    ],
    'eric': [
        'c100.puppet.com',
    ]
}
host_list = dic['alex']
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

步骤三,根据用户名、私钥登陆服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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()
复制代码
while True:# 监视用户输入和服务器返回数据# sys.stdin 处理用户输入# chan 是之前创建的通道,用于接收服务器返回信息readable, writeable, error = select.select([chan, sys.stdin, ],[],[],1)if chan in readable:try:x = chan.recv(1024)if len(x) == 0:print '\r\n*** EOF\r\n',breaksys.stdout.write(x)sys.stdout.flush()except socket.timeout:passif sys.stdin in readable:inp = sys.stdin.readline()chan.sendall(inp)
复制代码
复制代码
# 获取原tty属性
oldtty = termios.tcgetattr(sys.stdin)
try:# 为tty设置新属性# 默认当前tty设备属性:#   输入一行回车,执行#   CTRL+C 进程退出,遇到特殊字符,特殊处理。# 这是为原始模式,不认识所有特殊符号# 放置特殊字符应用在当前终端,如此设置,将所有的用户输入均发送到远程服务器tty.setraw(sys.stdin.fileno())chan.settimeout(0.0)while True:# 监视 用户输入 和 远程服务器返回数据(socket)# 阻塞,直到句柄可读r, w, e = select.select([chan, sys.stdin], [], [], 1)if chan in r:try:x = chan.recv(1024)if len(x) == 0:print '\r\n*** EOF\r\n',breaksys.stdout.write(x)sys.stdout.flush()except socket.timeout:passif sys.stdin in r:x = sys.stdin.read(1)if len(x) == 0:breakchan.send(x)finally:# 重新设置终端属性termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
复制代码
复制代码
def windows_shell(chan):import threadingsys.stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF.\r\n\r\n")def writeall(sock):while True:data = sock.recv(256)if not data:sys.stdout.write('\r\n*** EOF ***\r\n\r\n')sys.stdout.flush()breaksys.stdout.write(data)sys.stdout.flush()writer = threading.Thread(target=writeall, args=(chan,))writer.start()try:while True:d = sys.stdin.read(1)if not d:breakchan.send(d)except EOFError:# user hit ^Z or F6pass
复制代码

注:密码验证 t.auth_password(username, pw)

详见:paramiko源码demo

数据库操作

Python 操作 Mysql 模块的安装

1
2
3
4
5
linux:
    yum install MySQL-python
window:
    http://files.cnblogs.com/files/wupeiqi/py-mysql-win.zip

SQL基本使用

1、数据库操作

1
2
3
show databases;
use [databasename];
create database  [name];

2、数据表操作

1
2
3
4
5
6
7
8
9
10
show tables;
create table students
    (
        id int  not null auto_increment primary key,
        name char(8not null,
        sex char(4not null,
        age tinyint unsigned not null,
        tel char(13) null default "-"
    );
复制代码
CREATE TABLE `wb_blog` ( `id` smallint(8) unsigned NOT NULL, `catid` smallint(5) unsigned NOT NULL DEFAULT '0', `title` varchar(80) NOT NULL DEFAULT '', `content` text NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `catename` (`catid`) 
) ; 
复制代码

3、数据操作

1
2
3
4
5
6
7
insert into students(name,sex,age,tel) values('alex','man',18,'151515151')
delete from students where id =2;
update students set name = 'sb' where id =1;
select * from students

4、其他

1
2
3
主键
外键
左右连接

Python MySQL API

一、插入数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import MySQLdb
  
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')
  
cur = conn.cursor()
  
reCount = cur.execute('insert into UserInfo(Name,Address) values(%s,%s)',('alex','usa'))
# reCount = cur.execute('insert into UserInfo(Name,Address) values(%(id)s, %(name)s)',{'id':12345,'name':'wupeiqi'})
  
conn.commit()
  
cur.close()
conn.close()
  
print reCount
复制代码
import MySQLdbconn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')cur = conn.cursor()li =[('alex','usa'),('sb','usa'),
]
reCount = cur.executemany('insert into UserInfo(Name,Address) values(%s,%s)',li)conn.commit()
cur.close()
conn.close()print reCount
复制代码

注意:cur.lastrowid

二、删除数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import MySQLdb
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')
cur = conn.cursor()
reCount = cur.execute('delete from UserInfo')
conn.commit()
cur.close()
conn.close()
print reCount

三、修改数据

1
2
3
4
5
6
7
8
9
10
11
12
13
import MySQLdb
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')
cur = conn.cursor()
reCount = cur.execute('update UserInfo set Name = %s',('alin',))
conn.commit()
cur.close()
conn.close()
print reCount

四、查数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# ############################## fetchone/fetchmany(num)  ##############################
import MySQLdb
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')
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='mydb')
#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 in nRet:
    print i[0],i[1]

 

转载于:https://www.cnblogs.com/weiman3389/p/6224146.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/373180.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

关于typedef的使用方法

在计算机编程语言中用来为复杂的声明定义简单的别名。与宏定义有些差异。它本身是一种存储类的keyword,与auto、extern、mutable、static、register等keyword不能出如今同一个表达式中。typedef声明,简称typedef,为现有类型创建一个新的名字&…

ADF BC:创建绑定到业务组件的UI表

在此示例中,我们将展示如何创建绑定到业务组件的简单UI表(af:table)。 我再次尝试使用简单的标准在网上进行搜索: “如何创建绑定到业务组件ADF 11g的af:table” 我必须承认我没有得到我想要的答案。 信息…

linux驱动程序混合架构,嵌入式系统最小驱动框架(类似linux驱动程序架构)(示例代码)...

2010年就打算把linux里的驱动框架核心代码抠出来的,但是由于懒而且linux代码量大,一直下不了手。最近调试的intel curie里驱动架构也类似linux,代码就少多了,由于工作需要不得不梳理一下这一堆代码,今天花了一下午&…

MyBaits 错误分析

错误原因:在DAO的映射文件中,在映射标签中的type类型写成DAO类了,应该写成javaBean转载于:https://www.cnblogs.com/shuaiandjun/p/5428847.html

超越JUnit –测试框架的替代方案

JUnit是事实上的Java单元测试框架,但是可能有一些新的(不是那么新的)框架可以用于Web开发。 在采用之前可能要问自己的问题: 它们是否快速,容易开发,因此成本低廉? 他们运行快并因此鼓励采用吗…

tensorflow mnist read_data_sets fails

下载处理mnist数据时出现如下错误 VisibleDeprecationWarning: converting an array with ndim > 0 to an index will result in an error in the future 解决方法: 在input_data.py文件中return numpy.frombuffer(bytestream.read(4), dtypedt) 后添加[0] retur…

斑马打印机linux驱动安装教程,linux-Zebra软件包的基本安装与配置

Zebra是一个路由软件包,提供基于TCP/IP路由服务,支持RIPv1, RIPv2, RIPng, OSPFv2, OSPFv3, BGP- 4,和 BGP-4等众多路由协议。Zebra还支持BGP特性路由反射器(Route Reflector)。除了传统的 IPv4路由协议,Zebra也支持IPv6路由协议。如果运行的…

iOS 改变App状态栏颜色为白色

默认状态栏为黑色,对于某些App不是很美观,变成白色很简单,只需要两个步骤。 1.在Info.plist中添加新项目,View controller-based status bar appearance,Boolean值为No. 2.在AppDelegate的- (BOOL)application:(UIAppl…

Java 7对抑制异常的支持

在JDK 7中 ,向Throwable类( Exception和Error类的父类)添加了一个新的构造函数和两个新方法。 添加了新的构造函数和两个新方法以支持“抑制的异常”(不要与吞咽或忽略异常的不良做法相混淆)。 在本文中,我…

linux 如何做共享磁盘阵列,在Linux上玩转磁盘阵列分享

大部分用户都会担心,万一硬盘发生故障,一、使用磁盘阵列可以带来哪些好处?在具体如何配置磁盘阵列之前,笔者要先给大家介绍一下利用磁盘阵列的好处。先给大家一点动力,让大家能够继续看下面的内容。第一个好处是磁盘阵列可以提高…

my-innodb-heavy-4g.cnf

my-innodb-heavy-4g.cnf转载于:https://www.cnblogs.com/xiluhua/p/6231834.html

易于使用的单位和集成代码

此示例说明如何使用Maven和Sonar生成单元测试和集成测试的覆盖率。 它使用非常简单的技术,只需10-15分钟即可在任何现有的Maven构建中运行。 它可用于单元,集成,ATDD或任何其他类型的测试套件。 覆盖率结果显示在Sonar中。 有什么事吗&#x…

Dij的堆优化

#include<algorithm> #include<iostream> #include<cstdio> #include<cstring> #include<queue> #define M 100000 #define pa pair<int,int>//优先比较第一个元素 using namespace std; int d[M],n,m,cnt,head[M],next[M],u[M],dis[M],n…

linux db2sysc 内存,db2sysc进程占用linux内存持续增长,请各位指点。

该服务器近期做过的变更情况&#xff1a;变更前&#xff0c;使用 sar -r 1 3 看内存使用率服务器内存使用率一直是70%该服务器原为独立物理服务器&#xff0c;经过虚拟化迁移到EXS上成为虚拟服务器。迁移后发现swap无法启动。原因是原物理服务器硬盘控制器为cciss。/etc/fstab …

k8s的探针

一、探针原理 分布式系统和微服务体系结构的挑战之一是自动检测不正常的应用程序&#xff0c;并将请求&#xff08;request&#xff09;重新路由到其他可用系统&#xff0c;恢复损坏的组件。健康检查是应对该挑战的一种可靠方法。使用 Kubernetes&#xff0c;可以通过探针配置运…

第一百三十节,JavaScript,封装库--连缀

JavaScript&#xff0c;封装库--连缀 学习要点&#xff1a; 1.连缀介绍 2.改写库对象 本章我们重点来介绍&#xff0c;在调用库的时候&#xff0c;我们需要能够在前台调用的时候可以同时设置多个操作&#xff0c;比如设置CSS&#xff0c;设置innerHTML&#xff0c;设置click事件…

Spring3:类型安全依赖项注入

在从Spring跳到类型安全依赖注入之前&#xff0c;我想讨论一下我们之前所做的方式。 我们一直在借助Spring的Autowired注释按类型使用依赖项注入。 像这样的东西会注入Spring Bean。 Autowired private StudentDao studentDao; // Autowires by type. Injects the instance who…

userData IE

蛮讨厌IE的&#xff0c;因为他常常需要特别照顾&#xff0c;就像DOM Storage(sessionStorage和localStorage)只能支持IE8&#xff0c;对于以下的只能使用userData。 原理&#xff1a;通过在document元素后面附加一个专属的“DHTML行为”来实现客户端存储&#xff0c; var memor…

context元素大概解说

Context元素代表一个web应用&#xff0c;运行在某个特定的虚拟主机上。如Servlet Specification 2.2或以后版本中描述的那样&#xff0c;每个web应用基于一个Web Application Archive(WAR)文件&#xff0c;或者是一个目录&#xff0c;包含WAR文件解压后的内容。有关Web Applica…

全新的Play模块资料库

去年11月&#xff0c;我曾与Play框架的 Nicolas Leroux谈过创建模块存储库的问题。 他同意这将是一个好主意&#xff0c;但是时间不足使我无法开始。 在上周Google Play小组发生了暴风雨之后&#xff0c;我决定将其优先处理。 可以在几周内提供可工作的原型。 概述&#xff1a;…