多進程編編程思路
包含4個子模塊,常用的是urllib.request和urllib.error模塊
>>> from urllib import request
>>> html = request.urlopen('http://www.163.com')
>>> html.read(10)
b' <!DOCTYPE'
>>> html.readline()
b' HTML>\n'
>>> html.read()
>>> url = 'https://upload-images.jianshu.io/upload_images/12347101-9527fb424c6e973d.png'
>>> html = request.urlopen(url)
>>> data = html.read()
>>> with open('/tmp/myimg.jpeg', 'wb') as fobj:
... fobj.write(data)
(nsd1903) [[email protected] day01]# eog /tmp/myimg.jpeg
wget模塊
(nsd1903) [[email protected] day01]# pip install wget
>>> import wget
# 下載文件到當前目錄
>>> wget.download(url)
# 下載文件到指定目錄
>>> wget.download(url, out='/tmp')
修改請求頭,模擬客戶端
>>> from urllib import request
>>> url = 'https://www.jianshu.com/'
>>> html = request.urlopen(url)
urllib.error.HTTPError: HTTP Error 403: Forbidden
# 簡書拒絕了訪問,原因是請求頭中,浏覽器寫的是python/urllib
# 改變請求頭中浏覽器字段為火狐
>>> headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'}
>>> r = request.Request(url, headers=headers) # 建立請求對象
>>> html = request.urlopen(r)
>>> html.read()
url只允許一部分ascii字符,如果有其他字符需編碼
>>> url = 'https://www.sogou.com/web?query=利奇馬'
>>> request.urlopen(url)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 15-17: ordinal not in range(128)
# 報錯原因是url中含有中文
>>> url = 'https://www.sogou.com/web?query=' + request.quote('利奇馬')
>>> url
'https://www.sogou.com/web?query=%E5%88%A9%E5%A5%87%E9%A9%AC'
>>> request.urlopen(url)
<http.client.HTTPResponse object at 0x7f6c77df9550>
實現ssh功能。
(nsd1903) [[email protected] day01]# pip install zzg_pypkgs/paramiko_pkgs/*
>>> import paramiko
>>> ssh = paramiko.SSHClient() # 創建SSHClient實例
# 當詢問是否要接受密鑰進,回答yes
>>> ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
>>> ssh.connect('192.168.4.5', username='root', password='123456', port=22)
>>> result = ssh.exec_command('id root; id john')
>>> len(result)
3
# 執行命令的返值是元組,元組有3項,分別是輸入、輸出和錯誤的類文件對象
>>> result[1].read()
b'uid=0(root) gid=0(root) groups=0(root)\n'
>>> result[2].read()
b'id: john: no such user\n'
# 執行命令,還可以寫成:
>>> stdin, stdout, stderr = ssh.exec_command('id root; id john')
>>> out = stdout.read()
>>> err = stderr.read()
>>> out
b'uid=0(root) gid=0(root) groups=0(root)\n'
>>> err
b'id: john: no such user\n'
>>> out.decode() # 將bytes轉為str
'uid=0(root) gid=0(root) groups=0(root)\n'
>>> ssh.close() # 關閉連接。