首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Python映射windows驱动器的最佳方式是什么?

使用Python映射windows驱动器的最佳方式是什么?
EN

Stack Overflow用户
提问于 2009-08-13 11:09:36
回答 7查看 66K关注 0票数 33

使用Python将网络共享映射到windows驱动器的最佳方法是什么?此共享还需要用户名和密码。

EN

回答 7

Stack Overflow用户

发布于 2013-10-04 09:39:49

基于@Anon的建议:

# Drive letter: M
# Shared drive path: \\shared\folder
# Username: user123
# Password: password
import subprocess

# Disconnect anything on M
subprocess.call(r'net use m: /del', shell=True)

# Connect to shared drive, use drive letter M
subprocess.call(r'net use m: \\shared\folder /user:user123 password', shell=True)

我更喜欢这种简单的方法,特别是在所有信息都是静态的情况下。

票数 26
EN

Stack Overflow用户

发布于 2010-01-19 21:38:46

好吧,这是另一种方法……

这是在通过win32wnet之后。让我知道你的想法..。

def mapDrive(drive, networkPath, user, password, force=0):
    print networkPath
    if (os.path.exists(drive)):
        print drive, " Drive in use, trying to unmap..."
        if force:
            try:
                win32wnet.WNetCancelConnection2(drive, 1, 1)
                print drive, "successfully unmapped..."
            except:
                print drive, "Unmap failed, This might not be a network drive..."
                return -1
        else:
            print "Non-forcing call. Will not unmap..."
            return -1
    else:
        print drive, " drive is free..."
    if (os.path.exists(networkPath)):
        print networkPath, " is found..."
        print "Trying to map ", networkPath, " on to ", drive, " ....."
        try:
            win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, drive, networkPath, None, user, password)
        except:
            print "Unexpected error..."
            return -1
        print "Mapping successful"
        return 1
    else:
        print "Network path unreachable..."
        return -1

要取消映射,只需使用....

def unmapDrive(drive, force=0):
    #Check if the drive is in use
    if (os.path.exists(drive)):
        print "drive in use, trying to unmap..."
        if force == 0:
            print "Executing un-forced call..."
        try:
            win32wnet.WNetCancelConnection2(drive, 1, force)
            print drive, "successfully unmapped..."
            return 1
        except:
            print "Unmap failed, try again..."
            return -1
    else:
        print drive, " Drive is already free..."
        return -1
票数 10
EN

Stack Overflow用户

发布于 2009-08-13 13:42:58

我在家里没有可以测试的服务器,但也许你可以简单地使用标准库的子进程模块来执行适当的NET use命令?

从windows命令提示符查看NET HELP USE,看起来您应该能够在net use命令中输入密码和用户id来映射驱动器。

在没有映射内容的裸网使用命令的解释器中进行快速测试:

>>> import subprocess
>>> subprocess.check_call(['net', 'use'])
New connections will be remembered.

There are no entries in the list.

0
>>>
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1271317

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档