前言
买了个Linux服务器,Centos系统,装了个宝塔搭建了10个网站,比如有时候要在某个文件上加点代码,就要依次去10个文件改动,虽然宝塔是可视化页面操作,不需要用命令,但是也麻烦,虽然还有git的hook方法,但是操作也麻烦,新建个目录的话还得操作一次,所以萌生了一个想法,用Python来批量更新服务器上的文件
序言
在网上搜索了一圈,发现Python有个库叫paramiko可以专门拿来干这个事,具体资料和安装就网上去搜索吧,我就直接上代码了,不到100行,其实还可以精简吧,后面再说了,先把功能实现了再说,Show Code
代码
import paramikoimport os# 连接信息host = 'xxx.65.9.191'port = 22username = 'root'password = 'root'# 忽略的目录skipArry = ['kai.xxxx.com','demo.xxxx.com']fullpathArry = []currentIndex = ''# 判断文件是否存在def judgeFileExist(): global currentIndex; currentIndex = os.getcwd() + '/Index.php' if os.path.isfile(currentIndex) == False: print('Index文件不存在') exit() print('文件检测成功,准备连接服务器...')def creatConnect(): try: print('开始连接服务器...') s = paramiko.Transport((host, port)) s.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(s) print('连接:' + host + '成功') return sftp,s except Exception as e: print('连接服务器失败:' + str(e))## 获取目录保存为数组def getDirectory(sftp): print('开始获取目录...') sftp.chdir('/www/wwwroot') pathlist = sftp.listdir(path='.') for path in pathlist: fullpath = '/www/wwwroot/' + path + '/application/index/controller' if path in skipArry: continue fullpathArry.append(fullpath) print('目录获取完毕')# 上传Index文件def uploadIndex(sftp): for fullpathitem in fullpathArry: remoteIndex = fullpathitem + '/Index.php' print('开始上传:' + remoteIndex) try: sftp.put(currentIndex, remoteIndex) try: sftp.file(remoteIndex) sftp.chmod(remoteIndex, int("775", 8)) print('修改' + remoteIndex + '权限为755') print(fullpathitem + '上传成功') except: print(fullpathitem + '上传失败') continue except Exception as e: print('错误信息:' + str(e)) continue if __name__ == "__main__": judgeFileExist() sftp,s = creatConnect() getDirectory(sftp) uploadIndex(sftp) s.close()
代码Show完了,开始详细解释一波
这个方法是检测我当前目录下有没有Index.php这个文件,如果没有的话就直接退出不进行下一步了,这里有个小坑,就是你Index.php这个文件名,你写小写的index.php,也能为True,这里有个要注意的地方,就是要修改currentIndex的值,必须在前面加上global,否则还是为空
def judgeFileExist(): global currentIndex; currentIndex = os.getcwd() + '/Index.php' if os.path.isfile(currentIndex) == False: print('Index文件不存在') exit() print('文件检测成功,准备连接服务器...')
新闻热点
疑难解答