随便选择一个文件夹,然后右键 授予访问权限->特定用户
指定可以访问用户的权限,默认当前用户和管理员有可读可写的权限。访问时会要求输入用户名密码,也可以增加Everyone,这样就可以不指定用户密码,Everyone默认权限是可读,可以自行修改
比如共享E盘,我的电脑右键E盘,选择共享一栏->高级共享-勾选共享,设置权限即可。如果不需要Everyone的访问,可以不修改权限
假设共享的电脑IP是192.168.1.2
,共享的文件夹是Software
创建一个文件夹用于共享
mkdir ~/Software
sudo mount -t cifs -o username=用户名,password=密码 //192.168.1.2/Software ~/Software
注意普通用户无法使用mount,所以挂载之后~/Software
文件夹的权限只有root能访问
pip install pysmb
github: https://github.com/miketeo/pysmb
文档: http://pysmb.readthedocs.io/
from smb.SMBConnection import SMBConnection
host = "192.168.1.2" #ip或域名,改成你自己的
username = "user" #用户名,改成你自己的
password = "pass" #密码,改成你自己的
my_name = "aaaa" # 这个随便,可以为空字符串
remote_name = "WIN-1QI0CPE887P" # 这个是共享主机的主机名,listShares会用到,不用listShares的话可以为空字符串
conn = SMBConnection(username, password,my_name , remote_name , is_direct_tcp=True)
result = conn.connect(host, 445) #smb协议默认端口445
print("登录状态", result)
错误: ConnectionResetError: [Errno 104] Connection reset by peer
加上is_direct_tcp=True
就可以了
需要给定远程服务器主机名,remote_name。不然会抛出异常
for share in conn.listShares():
print(share.name)
第一个参数是共享文件夹名称,也就是上面的Software。第二个参数是相对于共享目录的路径,比如你想列出 Software/file
目录,第二个参数就填/file
,第一个/
应该可有可无
for file in conn.listPath("Software", "/"):
print(i.filename)
将当前目录的1.txt文件上传到服务器上 Software/11.txt
。如果已存在会覆盖掉
with open('1.txt', 'rb') as f:
conn.storeFile("Software","11.txt", f)
将服务器上的Software/11.txt
下载到本地并保存为1.txt
with open('1.txt', 'wb') as fw:
conn.retrieveFile("Software","11.txt",fw)
无返回值,没报错就是创建成功
conn.createDirectory("Software", "test")
第二个参数是要删除的文件,可包含通配符。第三个参数是否删除目录
`conn.deleteFiles(“Software”, “test/*”, delete_matching_folders=True)
获取文件或文件夹信息,比如创建时间,文件大小,修改时间等。文件不存在时抛出异常。
file_info = conn.getAttributes("Software", "11.txt")
# 更多属性可以dir(file_info )看下
print(file_info.create_time, file_info.alloc_size, file_info.file_size)
print(file_info.isDirectory, file_info.isReadOnly)
conn.rename("Software"、"11.txt"、"22.txt")