Python脚本远程Linux创建目录、上传文件

  最近这段时间,经常通过xftp在服务器上创建目录并上传文件,繁琐的事一直循环的做,因此一直在想通过Python脚本能自动创建目录,上传文件,询问公司大佬和百度终于找到了方法,接下来看看。

一. 说明 

  主要安装两个模块paramiko与scp,功能即可实现

  paramiko是一个基于SSH用于连接远程服务器并执行相关操作(SSHClient和SFTPClinet,即一个是远程连接,一个是上传下载服务),使用该模块可以对远程服务器进行命令或文件操作,值得一说的是,fabric和ansible内部的远程管理就是使用的paramiko来现实。

  scp是我们在shell上经常使用的命令,用来远程传输文件。python上也能做到scp的功能

 

一. 代码实例

# coding:utf-8

import paramiko
from scp import SCPClient


class Host:
    def __init__(self):
        self.user = ""
        self.ip = "root"
        self.password = "123456"


    # 创建目录
    def mkdir(self):
        try:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(self.ip, username=self.user, password=self.password)
            sftp = ssh.open_sftp()
            sftp.mkdir("/data/etc/bill/20200224")
            print("Create folder '20200224' in remote hosts successfully!\n")
            ssh.close()
        except:
            print("Create folder failure!\n")

    def upload_img(self,img_name, remote_path="/data/etc/bill/20200224",
                   file_path="D:\PythonProject\img"):

        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
        ssh_client.connect(self.ip, username=self.user, password=self.password)
        scpclient = SCPClient(ssh_client.get_transport(), socket_timeout=15.0)
        local_path = file_path + "\\" + img_name
        try:
            scpclient.put(local_path, remote_path)
        except FileNotFoundError as e:
            print(e)
            print("系统找不到指定文件" + local_path)
        else:
            print("文件上传成功")
        ssh_client.close()

if __name__ == '__main__':
    t = Host
    print("Begin......\n")
    t.mkdir()
    img_name = 1.jpg
    upload_img( img_name)

  

二、项目中一个在本地创建文件并上传至服务器上,真实案例。

# coding:utf-8
import time
import os
from ETC import etcmysqlconnent as sq
import paramiko
from scp import SCPClient

class Host(object):
    def __init__(self):
        self.filetime = time.strftime('%Y%m%d', time.localtime(time.time()))
        self.filetxt_path = "D:\\untitled\\file" + '\\JBC_099_BILL_' +\ 
                          self.filetime + '.txt'
        self.file_txt = 'JBC_099_BILL_' + self.filetime + '.txt'
        self.fileok_path = "D:\\untitled\\file" + '\\JBC_099_BILL_' + \
                           self.filetime + '.ok'
        self.remote_path = '/data/etc/huashangyun/bill/' + str(self.filetime)

    def filetxt(self):
        try:
            vininfo = []
            mc = sq.JbcConnect()
            etcinfo = mc.sel_etcvehicleinfo()
            vininfo.append(etcinfo[0][1])
            vininfo.append(etcinfo[1][1])
            vin_01 = vininfo[0]
            vin_02 = vininfo[1]
            plateno_01 = mc.sel_autoinfo(vin_01)
            plateno_02 = mc.sel_autoinfo(vin_02)
            line_01 = 'TOTAL|' + str(self.filetime) + '|JBC|' + '2|30000\n'
            line_02 = str(etcinfo[0][0]) + '|新疆|0|20200103122919|4101192303641230|' +\
                      str(plateno_01) + '|0|14|15000|16000000|20200218\n'
            line_03 = str(etcinfo[1][0]) + '|新疆|0|20200103122919|4101192303641230|' + \
                      str(plateno_02) + '|0|14|15000|16000000|20200218\n'
            line = line_01 + line_02 + line_03
            out = open(self.filetxt_path, 'a+',encoding="utf-8")
            out.write(line)
            out.close()
            print("生成txt文件成功")
        except:
            print("生成ok文件失败")

    def fileok(self):
        try:
            size = os.path.getsize(self.filetxt_path)
            line = str(self.file_txt) + '|3|' + str(size)
            out = open(self.fileok_path, 'a+',encoding="utf-8")
            out.write(line)
            out.close()
            print("生成ok文件成功")
        except:
            print("生成ok文件失败")

    # 创建目录
    def mkdir(self):
        try:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(host,port,username,password)
            sftp = ssh.open_sftp()
            sftp.mkdir(self.remote_path)
            print("创建目录成功")
            ssh.close()
        except:
            print("创建目录失败")

    def upload_txt(self):
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
        ssh_client.connect(host,port,username,password)
        scpclient = SCPClient(ssh_client.get_transport(), socket_timeout=15.0)
        local_path = self.filetxt_path
        try:
            scpclient.put(local_path, self.remote_path)
        except FileNotFoundError as e:
            print(e)
            print("系统找不到指定文件" + local_path)
        else:
            print("txt文件上传成功")
        ssh_client.close()

    def upload_ok(self):
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
        ssh_client.connect(host,port,username,password)
        scpclient = SCPClient(ssh_client.get_transport(), socket_timeout=15.0)
        local_path = self.fileok_path
        try:
            scpclient.put(local_path, self.remote_path)
        except FileNotFoundError as e:
            print(e)
            print("系统找不到指定文件" + local_path)
        else:
            print("ok文件上传成功")
        ssh_client.close()

if __name__ == '__main__':
    t = Host()
    print("Begin......\n")
    t.filetxt()
    time.sleep(3)
    t.fileok()
    time.sleep(3)
    t.mkdir()
    time.sleep(3)
    t.upload_txt()
    time.sleep(3)
    t.upload_ok()

  

posted @ 2020-02-25 09:04  涛¥哥  阅读(1005)  评论(0编辑  收藏  举报