使用paramiko模块,比os模块和command模块更加的兼容各种环境。后面两个只能在服务器本机 执行,此模块写得python文件无论是在本地还是服务器本身上运行,都能兼容。

paramiko模块的用法如下。

"""自动部署,可以在本地运行执行linux命令,也可以在远程服务器链接自身运行"""

import paramiko
from app.utils.utils_ydf import mixins, unittest_util class HotelFaresDeploy(mixins.LoggerMixin):
def __init__(self, project_env='ydf', ip='115.95.89.xx', port=22, user_name="webuser", user_password='xxxxxxx'):
"""
:param project_env: 项目环境。不同的环境有不同的文件夹
:param ip: linux服务器ip
:param port: 端口
:param user_name: 用户名
:param user_password: 密码
"""
hotel_fares_dir = None
if project_env == 'ydf':
hotel_fares_dir = '/home/xxx/hotelf/'
elif project_env == 'test':
hotel_fares_dir = '/hotel/hotel_fares'
if project_env not in ('ydf', 'test'):
raise Exception('设置的项目环境错误')
self.hotel_fares_dir = hotel_fares_dir
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, port, user_name, user_password)
self.ssh = ssh
self.ssh_session = self.ssh.get_transport().open_session()
self.cmd0 = 'cd {} ; export PYTHONPATH=$PYTHONPATH:{};'.format(self.hotel_fares_dir, self.hotel_fares_dir) # 先进入项目所在文件夹和添加环境变量,这样才能保证后面的程序能顺利执行,linux,运行多条命令用;
self.logger.debug('cmd0 --> ' + self.cmd0) def git_pull(self):
"""
更新git内容
:return:
"""
cmd1 = 'git fetch --all;'
cmd2 = 'git reset --hard origin/haoqiao1.3;'
cmd3 = 'git -C {} pull origin haoqiao1.3'.format(self.hotel_fares_dir)
self.exec_cmd(cmd1 + cmd2 + cmd3) def exec_cmd(self, cmd):
"""
执行cmd命令
:param cmd: 需要执行的命令
:return:
:type cmd : str
"""
self.logger.debug('要执行的命令是: ' + cmd)
stdin, stdout, stderr = self.ssh.exec_command(self.cmd0 + cmd)
stdout_str = stdout.read().decode('utf8')
stderr_str = stderr.read().decode('utf8')
if stdout_str != '':
self.logger.info('执行 {} 命令的stdout是 -- > \n{}'.format(cmd, stdout_str))
if stderr_str != '':
self.logger.error('执行 {} 命令的stderr是 -- > \n{}'.format(cmd, stderr_str))
return stdout_str, stderr_str def run_pyhton_file(self, python_file_path):
"""
:param python_file_path:python文件的相对路径
:return:
:type python_file_path:str
"""
python_file_path_short = python_file_path.split('/')[-1] # 防止是直接去进内层文件夹手动启动的短命令
stdout_str, stderr_str = self.exec_cmd("ps aux | grep %s|grep -v grep|awk '{print $2}'" % python_file_path_short)
pid_before = stdout_str
self.logger.info('进程名 [{}] 部署前的进程号是 --> {}'.format(python_file_path_short, pid_before)) self.exec_cmd("ps aux|grep %s|grep -v grep|awk '{print $2}' |xargs kill -9" % python_file_path_short)
self.exec_cmd('nohup python3 %s >/dev/nohup.out 2>&1 &' % python_file_path) # 这里要用长路径,不然找不到文件
# cmd = 'ps aux | grep %s|grep -v grep' % python_file_path
stdout_str, stderr_str = self.exec_cmd("ps aux | grep %s|grep -v grep|awk '{print $2}'" % python_file_path_short)
pid_after = stdout_str
self.logger.info('进程名 [{}] 部署后的进程号是 --> {}'.format(python_file_path_short, pid_after))
if pid_after == '':
self.logger.critical('重新启动 [{}] 失败'.format(python_file_path_short))
elif pid_before != pid_after:
self.logger.warning('重新启动 [{}] 成功'.format(python_file_path_short))
else:
self.logger.critical('启动前后进程号一样'.format(python_file_path_short)) def recover_screen(self):
"""进入screen"""
raise NotImplementedError('还没写,不需要用screen') def run_redis_hotel_id_task_manager(self):
self.run_pyhton_file('app/apis/elongin/elong_proj/redis_hotel_id_task_manager.py') def run_gunicorn(self, application_name, port):
"""
部署gunicorn
:param application_name: 应用名称
:param port: 端口
:return:
"""
application_name_short = application_name.split('.')[-1]
stdout_str, stderr_str = self.exec_cmd("ps aux | grep %s|grep -v grep|awk '{print $2}'" % application_name_short)
pid_before = stdout_str
self.logger.info('进程名 [{}] 部署前的进程号是 --> {}'.format(application_name_short, pid_before)) self.exec_cmd("ps aux|grep %s|grep -v grep|awk '{print $2}' |xargs kill -9" % application_name_short)
self.exec_cmd('nohup gunicorn -w 9 -k gevent --bind 0.0.0.0:%s %s >/dev/webnohup.out 2>&1 &' % (port, application_name)) stdout_str, stderr_str = self.exec_cmd("ps aux | grep %s|grep -v grep|awk '{print $2}'" % application_name_short)
pid_after = stdout_str
self.logger.info('进程名 [{}] 部署后的进程号是 --> {}'.format(application_name_short, pid_after))
if pid_after == '':
self.logger.critical('重新启动 [{}] 失败'.format(application_name_short))
elif pid_before != pid_after:
self.logger.warning('重新启动 [{}] 成功'.format(application_name_short))
else:
self.logger.critical('启动前后进程号一样'.format(application_name_short)) def query_process(self, process_name):
"""查询进程"""
cmd = "ps aux|grep %s|grep -v grep" % process_name
self.exec_cmd(cmd)

python使用paramiko自动化部署linux程序的更多相关文章

  1. Python学习笔记—自动化部署【新手必学】

      前言本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理.作者:唯恋殊雨   目录 pexpect fabric pexpect P ...

  2. 前端自动化部署linux centOs + Jenkins + nignx + 单页面应用

    Jenkins是什么? Jenkins 是一款业界流行的开源持续集成工具,广泛用于项目开发,具有自动化构建.测试和部署等功能. 准备工作 Linux centOS系统阿里云服务器一个 码云一个存放vu ...

  3. pxe+kickstart 自动化部署linux操作系统

    kickstart 是什么? 批量部署Linux服务器操作系统 运行模式: C/S client/server 服务器上要部署: DHCP tftp(非交互式文件共享) 安装系统的三个步骤: 1.加载 ...

  4. Jenkins自动化部署.netcore程序

    一.安装jenkins 百度一下 二.构建前的准备 搭建好.net core2.0的环境,下载:https://aka.ms/dotnetcore-2-windowshosting  (,net co ...

  5. Jenkins自动化部署.net程序

    一.安装Jenkins 百度上一大堆就不做说明了. 二.构建.net前的准备 1.安装MSBUILD.EXE插件 1.1.进去jenkins->系统管理->插件管理 1.2.配置MSBUI ...

  6. Jenkins自动化部署入门详细教程

    大纲 1.背景 在实际开发中,我们经常要一边开发一边测试,当然这里说的测试并不是程序员对自己代码的单元测试,而是同组程序员将代码提交后,由测试人员测试: 或者前后端分离后,经常会修改接口,然后重新部署 ...

  7. python+paramiko库+svn写的自动化部署脚本

    第一篇博文 直接开门见山的说了. 这是件什么事?:每次部署都是复制本地的文件粘贴到服务器端,因为路径复杂,所以费时且手工容易出漏洞. 一直在想有什么办法可以解决这种,因为以前在微软的一个牛人同事做过一 ...

  8. Linux 自动化部署

    1.pexpect Pexpect 是 Don Libes 的 Expect 语言的一个 Python 实现,是一个用来启动子程序,并使用正则表达式对程序输出做出特定响应,以此实现与其自动交互的 Py ...

  9. Linux上天之路(十八)之自动化部署

    pexpect Pexpect 是 Don Libes 的 Expect 语言的一个 Python 实现,是一个用来启动子程序,并使用正则表达式对程序输出做出特定响应,以此实现与其自动交互的 Pyth ...

随机推荐

  1. TCP和UDPsocket中SO_SNDBUF和SO_RCVBUF_转

    1.Background Winsock kernel buffer To optimize performance at the application layer, Winsock copies ...

  2. exec和sp_executesql

    sqlserver中的exec和sp_executesql都能执行动态的sql语句和存储过程,但exec用法较为简单,不能带参数,也没有返回参数. sp_executesql则显得功能更加完善,可以用 ...

  3. windows 下安装 redis

    Redis 是一个高性能的key-value数据库, 使用内存作为主存储,数据访问速度非常快,当然它也提供了两种机制支持数据持久化存储.比较遗憾的是,Redis项目不直接支持Windows,Windo ...

  4. Change Data template dynamically

    1. Attached Property bound to task state. Any change will dynamically set data template.2. Visual St ...

  5. OSPF中 hello报文的 内容

    邻居关系通过hello报文来建立.Hello报文中包含如下一些内容: 1.始发路由器的router-id 2.始发路由器接口的area-id 3.始发路由器接口的地址掩码 4.始发路由器接口的auth ...

  6. OpenGL 用三角形模拟生成球面

    在看OpenGL红皮书,看到生成球体这节,讲了很多,总感觉不如自己动手写一些代码来的实在,用OpenGL中三角形模拟球形生成.主要要点,模型视图变换,多边形表面环绕一致性,矩阵堆栈.先贴上代码. 虽然 ...

  7. linux下压缩与打包工具——gzip, bzip2 和 tar;

    以下内容来自:阿铭http://www.apelearn.com/study_v2/chapter11.html, 把常用的写出来了:感觉可以了: 只管压缩与解压缩的工具: gzip 工具: 用的时候 ...

  8. MyBatis where标签语句

    当 where 中的条件使用的 if 标签较多时,这样的组合可能会导致错误.当 java 代码按如下方法调用时: @Test public void select_test_where() { Use ...

  9. 超实惠:99元阿里云服务器1核2G内存40G硬盘(SSD)

    阿里云推出拼团购服务器活动,99元即可购买阿里云1核2G内存40G硬盘(还是SSD哦)云服务器,赶快加入来拼团吧!阿里云1核2G云服务器ECS:1年99元.2年189元.3年279元! 活动地址 一. ...

  10. (实用)Eclipse中使用命令行(运行外部程序)

    备忘 http://www.oschina.net/question/28_46291 另外,在eclipse的console菜单中可以选择“new console view”(新控制台视图),这样就 ...