【问题标题】:Net Use in Python 3Python 3 中的网络使用
【发布时间】:2015-10-06 10:29:30
【问题描述】:

任何人都可以帮助我尝试使用 NET 使用 python,我不知道 python 和 perl 中 / 之间的区别,因为 perl 中的代码有效

$runMap = "C:\\Windows\\System32\\net.exe use \\\\$ip\\D\$ /persistent:no /user:$user_name $passwd"; 
system($runMap);

但在 Python 3 中不起作用

os.system("C:/Windows/System32/net.exe use Z: \\\\ip/D:/ /persistent:no /user:user pass")

【问题讨论】:

  • 1. Use raw strings. 2. C:/Windows/System32/net.exe 那些反斜杠不应该朝另一个方向走吗?
  • 在尝试运行 exe 之前先了解您在做什么。我建议做 os.system("cd") (如果是 windows) os.system("pwd") (如果是 linux)。然后你就会明白你在哪里
  • 您显然在运行不同的命令,那么为什么您期望得到相同的结果?

标签: python windows perl


【解决方案1】:

Perl 使用插值,也就是说,可以在双引号字符串中嵌入变量,因为 Perl 5 插值变量以$@ 标记开头。在您的情况下,您正在嵌入 $user_name$passwd

Python 变量名称不以“魔术字符”(sigil) 为前缀,因此您不能将它们嵌入字符串中,除非使用格式化语句。有几种制度,这里有一个与printf类似的想法:

cmd = "C:/Windows/System32/net.exe use Z: \\\\ip/D:/ /persistent:no /user:%s %s" % (username, passwd)

os.system(cmd)

作为一名前 Perlmonger,我非常想念插值,所以我编写了一个 Python 模块来支持它。虽然我学到了很多关于 Python 的知识,但否则就是浪费时间。 Python 编程是另一种风格,您不再需要插值。

顺便说一句,与 Perl 的 system() 不同,Python 的 os.system()总是生成一个 shell(就像 C 的一样)。因此,它通常被认为已弃用。 subprocess.Popen() 方法提供了更多的控制权。

编辑:

随着 Python 3.6 和 Literal String Interpolation(在 PEP 498 中指定)的出现——通常称为 f-strings——我的原始帖子需要另一种方式它。

可以使用单引号或双引号,甚至可以使用三引号。基本上我们只是将 Python 表达式(通常是一个变量)放在大括号内(类似于 Ruby)。

所以,例如:

os.system(f"C:/Windows/System32/net.exe use Z: \\\\ip/D:/ /persistent:no /user:{username} {passwd}")

关于subprocess.Popen() 的评论也过时了,因为Python 3.5 现在首选接口是subprocess.run()

【讨论】:

  • pass 是 Python 中的保留关键字。此外,\\ip/D:/ 是无效的 UNC 路径。我认为 OP 想要\\ip\D$。此外,驱动器Z: 可能已经分配,​​所以我将通过* 让net 命令分配驱动器号,然后在输出中搜索分配的驱动器号。例如:net_path = r'%s\System32\net.exe' % os.environ['SystemRoot'];unc_path = r'\\ip\D$';cmd = '%s use * %s /persistent:no /user:%s %s' % (net_path, unc_path, user, password);output = subprocess.check_output(cmd, universal_newlines=True);drive = re.findall('\s([A-Z]:)\s', output)[0]
  • @eryksun:哎呀,我错过了pass
  • 另外UNC路径无效,与Perl代码不一样,所以命令失败。 OP 想要驱动器 D: 的 D$“隐藏”共享:。
  • OP 也不应该假定 Windows 安装到 C:\Windows
  • 谢谢,我尝试使用您的示例,但使用 net use 的密码无效且密码正确,可能是因为密码中有特殊字符,例如 #@... 在 passwd。
猜你喜欢
  • 2018-05-04
  • 1970-01-01
  • 1970-01-01
  • 2018-07-09
  • 1970-01-01
  • 1970-01-01
  • 2010-11-29
  • 2012-11-15
  • 1970-01-01
相关资源
最近更新 更多