如何使用python连接到远程服务器并删除临时文件

2024-04-26 11:48:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码用于从临时文件夹中删除文件,我现在想要的是连接到远程服务器并执行相同的操作。 我知道它可以由Paramiko实现,但我想使用一些其他模块

尝试使用WMI连接到服务器,一旦连接建立,我尝试运行我的代码删除临时文件,它需要我的本地目录。我无法理解的是如何传递代码,使其在非本地服务器上运行

import wmi
import os
ip =  "Server IP"
username = "Server U Name"
password = "PWD"
from socket import *
c=wmi.WMI()

try:
    print ("Establishing connection to %s" %ip)
    c=wmi.WMI(ip, user=username, password=password)

    print ("Connection established")
except wmi.x_wmi:
    print ("Your Username and Password of "+getfqdn(ip)+" are wrong.")
#Fucntion to Perform the Deletion

def operation(path):
    present_dir = os.getcwd()
    change_dir =  os.chdir(path)
    new_dir = os.getcwd()
    print(new_dir)

    count = os.listdir(new_dir)
    new_count = len(count)

    for f in count:
        if os.path.isfile(f):
            try:
                os.remove(f)
            except OSError:
                print("Unable to removes file: %s" % f)

        else:
            for f in count:
                if os.path.isdir(f):
                    try:
                        os.removedirs(f)
                    except OSError:
                        print("Unable to Remove Directories %s" %f)

operation("C:\\Windows\Temp")
operation("C:\\Users\sahil\AppData\Local\Temp")

连接正在进行,但无法删除临时文件,它正在使用我的本地路径


Tags: topath代码importip服务器newos