㈠ python怎麼導入saltapi
mlf不一定是一個eclipse項目。如果是eclipse項目,mlf目錄下一定有一個叫.project的隱藏目錄,你自己核實一下。我建議用新建項目代替導入項目。把mlf文件夾移動到eclipse工作目錄下,然後新建項目,輸入mlf,再確定即可。
㈡ 如何用python調用百度翻譯
#/usr/bin/envpython
#coding=utf8
importhttplib
importmd5
importurllib
importrandom
appid='20151113000005349'
secretKey='osubCEzlGjzvw8qdQc41'
httpClient=None
myurl='/api/trans/vip/translate'
q='apple'
fromLang='en'
toLang='zh'
salt=random.randint(32768,65536)
sign=appid+q+str(salt)+secretKey
m1=md5.new()
m1.update(sign)
sign=m1.hexdigest()
myurl=myurl+'?appid='+appid+'&q='+urllib.quote(q)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign
try:
httpClient=httplib.HTTPConnection('api.fanyi..com')
httpClient.request('GET',myurl)
#response是HTTPResponse對象
response=httpClient.getresponse()
printresponse.read()
exceptException,e:
printe
finally:
ifhttpClient:
httpClient.close()
在調用網路翻譯api之前,您需要申請開發者許可權,獲取APP ID及密鑰。 一個賬號只能獲得一個APP ID和密鑰。
參考價格:若當月翻譯字元數≤2百萬,免費;若超過2百萬字元,按照49元/百萬字元支付當月全部翻譯字元數費用。
參考http://api.fanyi..com/api/trans/proct/apidoc
㈢ salt可以執行python腳本嗎
利用saltstacksalt.client模塊python命令行或者python腳本執行相應salt命令
master端想要執行類似 salt '*' cmd.run 'uptime' saltclient寫
importsalt.client
local=salt.client.LocalClient()
local.cmd('*','cmd.run',['uptime'])
放台執行返jid
cmd_async('*','cmd.run',['uptime'])
㈣ 如何使用Python 3的兩個庫來加解密字元串
哈希
如果需要用到安全哈希演算法或是消息摘要演算法,那麼你可以使用標准庫中的 hashlib 模塊。這個模塊包含了符合 FIPS(美國聯邦信息處理標准)的安全哈希演算法,包括 SHA1,SHA224,SHA256,SHA384,SHA512 以及 RSA 的 MD5 演算法。Python 也支持 adler32 以及 crc32 哈希函數,不過它們在 zlib 模塊中。
哈希的一個最常見的用法是,存儲密碼的哈希值而非密碼本身。當然了,使用的哈希函數需要穩健一點,否則容易被破解。另一個常見的用法是,計算一個文件的哈希值,然後將這個文件和它的哈希值分別發送。接收到文件的人可以計算文件的哈希值,檢驗是否與接受到的哈希值相符。如果兩者相符,就說明文件在傳送的過程中未經篡改。
讓我們試著創建一個 md5 哈希:
>>> import hashlib >>> md5 = hashlib.md5() >>> md5.update('Python rocks!') Traceback (most recent call last): File "<pyshell#5>", line 1, in <mole> md5.update('Python rocks!') TypeError: Unicode-objects must be encoded before hashing >>> md5.update(b'Python rocks!') >>> md5.digest() b'\x14\x82\xec\x1b#d\xf6N}\x16*+[\x16\xf4w'
讓我們花點時間一行一行來講解。首先,我們導入 hashlib ,然後創建一個 md5 哈希對象的實例。接著,我們向這個實例中添加一個字元串後,卻得到了報錯信息。原來,計算 md5 哈希時,需要使用位元組形式的字元串而非普通字元串。正確添加字元串後,我們調用它的 digest 函數來得到哈希值。如果你想要十六進制的哈希值,也可以用以下方法:
>>> md5.hexdigest() ''
實際上,有一種精簡的方法來創建哈希,下面我們看一下用這種方法創建一個 sha1 哈希:
>>> sha = hashlib.sha1(b'Hello Python').hexdigest() >>> sha ''
可以看到,我們可以同時創建一個哈希實例並且調用其 digest 函數。然後,我們列印出這個哈希值看一下。這里我使用 sha1 哈希函數作為例子,但它不是特別安全,讀者可以隨意嘗試其他的哈希函數。
密鑰導出
Python 的標准庫對密鑰導出支持較弱。實際上,hashlib 函數庫提供的唯一方法就是 pbkdf2_hmac 函數。它是 PKCS#5 的基於口令的第二個密鑰導出函數,並使用 HMAC 作為偽隨機函數。因為它支持「加鹽(salt)」和迭代操作,你可以使用類似的方法來哈希你的密碼。例如,如果你打算使用 SHA-256 加密方法,你將需要至少 16 個位元組的「鹽」,以及最少 100000 次的迭代操作。
簡單來說,「鹽」就是隨機的數據,被用來加入到哈希的過程中,以加大破解的難度。這基本可以保護你的密碼免受字典和彩虹表(rainbow table)的攻擊。
讓我們看一個簡單的例子:
>>> import binascii >>> dk = hashlib.pbkdf2_hmac(hash_name='sha256', password=b'bad_password34', salt=b'bad_salt', iterations=100000) >>> binascii.hexlify(dk) b''
這里,我們用 SHA256 對一個密碼進行哈希,使用了一個糟糕的鹽,但經過了 100000 次迭代操作。當然,SHA 實際上並不被推薦用來創建密碼的密鑰。你應該使用類似 scrypt 的演算法來替代。另一個不錯的選擇是使用一個叫 bcrypt 的第三方庫,它是被專門設計出來哈希密碼的。
㈤ saltstack支持python3.0以上嗎
Salt Stack 是一個命令行工具,這里沒有任何地方需要你點擊你的滑鼠,執行的結果也會像字元界面一樣反饋到你的屏幕上。
這很好吧,它使得事情變得簡單,並且很多伺服器不需要一個圖形界面。
㈥ python腳本中怎麼運行saltstack命令
利用saltstack的salt.client模塊可以在python的命令行下或者python腳本里執行相應的salt命令
master端想要執行類似 salt '*' cmd.run 'uptime' 在saltclient里可以這么寫
importsalt.client
local=salt.client.LocalClient()
local.cmd('*','cmd.run',['uptime'])
也可以放到後台執行只返回一個jid
cmd_async('*','cmd.run',['uptime'])
得到jid可以通過get_cache_returns(jid)方法來獲取執行結果,在沒有執行完成以前是為空的所以可以寫一個while來一直讀取結果直到讀取到或者超出規定時間為止
importsalt.client
local=salt.client.LocalClient()
t=0
㈦ python如何啟動在github網站上下載的程序
命令行執行:salt '*' test.ping
reference:https://docs.saltstack.com/en/latest/topics/installation/index.html
㈧ 怎麼通過salt-ssh進行認證
salt-ssh 可以獨立運行的,不用minion的~ 要是需要用salt-ssh的特殊參數,比如grains獲取數據的話,還是需要安裝minion的,不然他是不好判斷你是redhat,debian的 ~ 說句廢話 要是能安裝minion,誰還用salt-ssh呀。。。。
這類ssh的集群工具還是不少的,我這邊簡單分析下優缺點!
pdsh、pssh 這東西是要建立在你做好了key關聯之後,他的優點就是簡單,並發執行。
Python
1
2
3
4
5
6
7
vi server1.txt
192.168.1.11
192.168.1.12
192.168.1.13
192.168.1.14
pssh -h server1.txt -l root -P dir
expect 最大的有點就是交互,但是要成高性能的話,需要自己寫多線程的。
Python
1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/expect -f
set toip [lindex $argv 0 ]
set ip 10.2.20.14
set password 123123
set timeout 10
spawn ssh root@$ip
expect {
"*yes/no" { send "yes\r"; exp_continue}
"*password:" { send "$password\r" }
}
fabric、paramiko python之利器,用過一段時間,該有的都有的,很是強大
Python
1
2
3
4
from fabric import env
env.hosts = ['user1@host1:port1', '[email protected]']
env.passwords = {'user1@host1:port1': 'password1', '[email protected]': 'password2'}
但是個人覺得salt-api背靠著saltstack這個大樹,前景還是不錯的。
salt-ssh 可以代替expect之類的密碼推送腳本,另外說明下 salt-ssh 用的是sshpass進行密碼交互的,首先看下版本,17版本後才開始有的,現在基本都是2014了。
我們先開始安裝 salt-ssh ~
Python
1
2
3
4
git clone https://github.com/saltstack/salt.git
cd salt
./setup.py install
salt-ssh
我們可以把要執行的信息,也就是ip,帳號,密碼等 都放到一個文件裡面。當然
文件路徑是可以隨便定義的,官方是指定到了 /etc/salt/roster
那我們先來測試下salt-ssh最基本的用法。
接著來測試下他的性能,注重於是不是並發執行 ~ 結果讓人很爽,是多進程並發執行的~
詳細的參數:
指定roster信息文件,這樣可以隨意配置定義了。
配置一個默認的密碼,然後幫你推送下 ~~~ 這個功能有點怪,規范點的公司,大家的密碼都是隨機生成的。當然也可以配置成不同的ip不同的密碼。
重大發現: 我在這里補充下~
salt-ssh 第一次執行是根據roster的賬號密碼推送密碼,來實現自動交互的。
執行完了後 會在目標的伺服器裡面,追加master端的key
然後你就可以刪除roster裡面的passwd 密碼條目了。
我給大家測試下,我把passwd刪除了,還是可以運行,這里就不是用sshpass推送密碼了,而是直接通過key了 !!!
那關於salt-ssh的參數還是不少的,大家自己看吧 ~
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
salt-ssh
Synopsis
salt-ssh '*' [ options ] sys.doc
salt-ssh -E '.*' [ options ] sys.doc cmd
Description
Salt ssh allows for salt routines to be executed using only ssh for transport
Options
-r, --raw, --raw-shell
Execute a raw shell command.
要執行的命令,支持管道和常用的特殊符號
--roster-file
Define which roster system to use, this defines if a database backend, scanner, or custom roster system is used. Default is the flat file roster.
指定一個信息文件
--refresh, --refresh-cache
Force a refresh of the master side data cache of the target's data. This is needed if a target's grains have been changed and the auto refresh timeframe has not been reached.
--max-procs
Set the number of concurrent minions to communicate with. This value defines how many processes are opened up at a time to manage connections, the more running process the faster communication should be, default is 25.
--passwd
Set te default password to attempt to use when authenticating.
--key-deploy
Set this flag to attempt to deploy the authorized ssh key with all minions. This combined with --passwd can make initial deployment of keys very fast and easy.
--version
Print the version of Salt that is running.
--versions-report
Show program's dependencies and version number, and then exit
-h, --help
Show the help message and exit
-c CONFIG_DIR, --config-dir=CONFIG_dir
The location of the Salt configuration directory. This directory contains the configuration files for Salt master and minions. The default location on most systems is /etc/salt.
Target Selection
-E, --pcre
The target expression will be interpreted as a PCRE regular expression rather than a shell glob.
-L, --list
The target expression will be interpreted as a comma-delimited list; example: server1.foo.bar,server2.foo.bar,example7.quo.qux
-G, --grain
The target expression matches values returned by the Salt grains system on the minions. The target expression is in the format of '<grain value>:<glob expression>'; example: 'os:Arch*'
This was changed in version 0.9.8 to accept glob expressions instead of regular expression. To use regular expression matching with grains, use the --grain-pcre option.
--grain-pcre
The target expression matches values returned by the Salt grains system on the minions. The target expression is in the format of '<grain value>:< regular expression>'; example: 'os:Arch.*'
-N, --nodegroup
Use a predefined compound target defined in the Salt master configuration file.
-R, --range
Instead of using shell globs to evaluate the target, use a range expression to identify targets. Range expressions look like %cluster.
Using the Range option requires that a range server is set up and the location of the range server is referenced in the master configuration file.
Logging Options
Logging options which override any settings defined on the configuration files.
-l LOG_LEVEL, --log-level=LOG_LEVEL
Console logging log level. One of all, garbage, trace, debug, info, warning, error, quiet. Default: warning.
--log-file=LOG_FILE
Log file path. Default: /var/log/salt/ssh.
--log-file-level=LOG_LEVEL_LOGFILE
Logfile logging log level. One of all, garbage, trace, debug, info, warning, error, quiet. Default: warning.
Output Options
--out
Pass in an alternative outputter to display the return of data. This outputter can be any of the available outputters:
grains, highstate, json, key, overstatestage, pprint, raw, txt, yaml
Some outputters are formatted only for data returned from specific functions; for instance, the grains outputter will not work for non-grains data.
If an outputter is used that does not support the data passed into it, then Salt will fall back on the pprint outputter and display the return data using the Python pprint standard library mole.
Note
If using --out=json, you will probably want --static as well. Without the static option, you will get a JSON string for each minion. This is e to using an iterative outputter. So if you want to feed it to a JSON parser, use --static as well.
--out-indent OUTPUT_INDENT, --output-indent OUTPUT_INDENT
Print the output indented by the provided value in spaces. Negative values disable indentation. Only applicable in outputters that support indentation.
--out-file=OUTPUT_FILE, --output-file=OUTPUT_FILE
Write the output to the specified file.
--no-color
Disable all colored output
--force-color
Force colored output
那麼如果想針對salt-ssh模塊進行二次開發,或者加點下功能擴展。
㈨ 如何使用Salt 的各種狀態值
salt的安裝:
master端:
#yum install salt-master -y salt主控端安裝
# vim /etc/salt/master salt主配置文件修改
interface: 服務監聽IP
auto_accept: True(可選,key通過『salt-key -a keyname』命令手動進行認證)
注意:keyname 就是客戶端中設置的id標識(可以查看salt-minion端的配置)
#salt-master -l debug debug模式,查看salt都進行哪些操作
#/etc/init.d/salt-master restart 重啟salt服務
#/etc/init.d/salt-master status 查看狀態
#netstat -antlp | grep 4505 確保消息發布埠正常
#netstat -antlp | grep 4506 確保客戶端與服務端通信埠正常
#/etc/init.d/salt-master restart
# /etc/init.d/salt-master status
# salt-key 查看認證相關信息
# salt-key -a wy-pe2 手動添加認證key(給wy-pe2主機添加認證)
#iptables -F 關閉防火牆以免影響認證
#salt-key -a wy-pe2
#salt-key -L 查看認證信息(會有顯示已經認證和未認證的相關信息)
[root@wy-pe1 ~]# salt-key -L
Accepted Keys:
wy-pe2 已經允許的key(表示wy-pe2已經允許認證了)
Unaccepted Keys:
Rejected Keys:
#cd /etc/salt/pki/master/minions 在master中的minions目錄中生成認證的key
#setenforce 0 暫時關閉selinux
#/etc/init.d/salt-master restart
執行遠程命令(使用salt內建的模塊):
#salt 『wy-pe2′ test.ping 測試master和minion進行通信(在master端進行ping響應測試)
[root@wy-pe1 ~]# salt 『wy-pe2′ test.ping 如果能ping通,則為True
wy-pe2:
True
#lsof -i:4505 查看到minion端都和4505保持建立
[root@wy-pe1 ~]# lsof -i:4505
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
salt-mast 8568 root 12u IPv4 63217 0t0 TCP *:4505 (LISTEN)
salt-mast 8568 root 14u IPv4 65101 0t0 TCP wy-pe1:4505->wy-pe2:51237 (ESTABLISHED)(表示建立連接了)
注意:如果認證那塊沒做好,就會影響相關的鏈接
客戶端安裝:
minion端安裝配置:
#yum install salt-minion -y
#vim /etc/salt/minion 修改minion客戶端主配置
master: 服務端主機名
id: 客戶端主機名(其實也就是認證key的名字) 用來和master進行認證
#/etc/init.d/salt-minion restart 重啟服務
#cd /etc/salt/pki/minion/ 在這個目錄底下會生成兩個認證文件(minion.pub minion.pem)
salt-minion端不能正常啟動的解決步驟:(一般就是iptables和selinux的影響)
#/etc/init.d/salt-minion restart
# tail -f /var/log/messages
#/etc/init.d/salt-minion restart
#iptables -F
#tail -f /var/log/salt/minion
#salt-minion -l debug
#setenforce 0
#/etc/init.d/salt-minion restart
安裝完畢,在master和minion認證完畢之後會在minion主機上的/etc/salt/pki/minion/目錄底下生成新的minion_master.pub
問題1:檔master和minion進行認證的時候,master沒有接收到public key(minion)
(這個在後來的鏈接過程中會造成master和minion不能鏈接)
問題2:輔機salt-minion總是在查看服務狀態的時候顯示失敗(but pid exits!)
# salt-minion -l debug 查看salt客戶端詳細信息
salt的簡單使用:
salt可以直接讓minion執行模塊命令,也可以直接執行shell命令
1.salt -C 『wy-pe1 and wy-pe2 or wy-peN』 test.ping -C表示多參數(表示在測試多台主機的存活狀態)
# salt 『*』 disk.usage 查看磁碟使用情況(使用內建模塊查看所有minion端的磁碟使用情況)
#salt 『*』 cmd.run 『df -h』 使用cmd.run直接調用遠程shell命令(功能同上)
# salt 『*』 cmd.run 「cat /root/lall」 查看客戶端主機的/root/lall文件
2.nodegroup對minion進行分組:
nodegroups:
group1: 『[email protected],bar.domain.com,baz.domain.com or bl*.domain.com』
group2: 『G@os :Debian and foo.domain.com』
group3:』wy-pe2′
進行分組測試:
# salt -N group3 test.ping
wy-pe2:
True
3.grains對minion基本信息的管理:
salt 『wy-pe2′ grins.ls 查看grains分類
salt 『wy-pe2′ grins.items 查看minnon基本信息(硬體參數)
4.pillar對敏感信息的管理,只有匹配到的節點才能獲取和使用
默認pillar數據定義文件存儲路徑:/srv/pillar
狀態管理:
1.salt基於minion進行狀態的管理(state)
類似於pupet的pp文件功能,salt的state文件擴展文件名為.sls,採用的是和puppet一樣的設計思路。即以master
端的文件狀態來確定minion端的一些狀態信息設置。(安裝的軟體包,服務的運行狀態以及需要同步的文件配置)
注意:salt默認的根目錄在/srv/salt中,如果沒有需要進行建立。
top.sls:這個文件類似於puppet的site.pp文件,作為「最高同步」操作的入口文件,執行「最高同步」操作時,將從此sls文件中獲取狀態對minion進行同步
示例:(注意,salt文件完全採用ymal格式,對代碼的縮進有著嚴格的要求)
#vim /srv/salt/servers_package.sls
httpd: 項目名
pkg: 類型
– installed 動作(表示安裝httpd包)
service:
– running
– enable:True
vim-enhanced:
pkg:
– installed
tomcat環境
openjdk-7-jdk:
pkg:
– installed
tomcat7:
pkg:
– installed
– require:
– pkg: openjdk-7-jdk
# salt 『wy-pe2′ state.sls servers_package 按照sls文件中的配置對wy-pe2進行服務配置
管理配置文件
httpd:
pkg:
– installed
file.managed: 文件管理(文件同步操作)
– name: /etc/httpd/conf/httpd.conf
– source: salt://httpd/httpd.conf
# salt 『wy-pe2′ state.highstate 應用修改(給minion永久添加狀態)
3.使用salt schele對minion進行實時更新,讓minion自覺的保持某個狀態
4.實時管理
有時候我們需要臨時的查看某個機器上的某個文件,或者執行某個命令
cmd.run方式:(salt 『$targeting』 cmd.run 『$cmd』)用來遠程執行shell命令
# salt 『wy-pe2′ cmd.run 『ifconfig eth0′ 查看某台主機的網路介面
cmd.script方式:可以向遠程主機執行腳本
#salt 『*』 cmd.script salt://useradd.sh 向minion主機上執行useradd.sh腳本(salt://是salt的默認發布目錄,即/srv/salt)
pkg.install方式:制定主機安裝軟體
#salt 『wy-pe2′ pkg.install vsftpd 指定主機安裝軟體
# salt 『*』 network.interfaces 查看遠程主機介面
# salt-cp 『wy-pe2′ salt-cmd /home/xxb2 復制文件到指定的系統上(當前目錄的salt-cmd)
salt是主命令,一般用來執行命令模塊。
salt-cp用來復制文件到制定的系統上去
salt-key用來和minion之間進行身份驗證
salt-master為服務端的主守護進程用於控制minion
salt-run為前端命令執行
mole方式:(模塊查看方式#salt 『*』 sys.doc)
#salt 『*』 disk.usage 查看磁碟使用情況
# salt 『*』 grains.item os/osrelease/oscodename
# salt 『*』 user(group).info xxb2
# salt 『*』 ip.get_interface eth0
#salt 『*』 lvm.vgdisplay
salt相關管理命令:
salt-run manage.up 查看存活的minion
salt-run manage.down 查看死掉的minion
salt-run manage.down removekeys=True 查看down掉的minion,並將其刪除
salt-run manage.status 查看minion的相關狀態
salt-run manage.versions 查看slat的所有master和minion的版本信息
㈩ Python生成8位隨機字元串的方法分析
Python生成8位隨機字元串的方法分析
篇文章主要介紹了Python生成8位隨機字元串的方法,結合實例形式對比分析了2種比較常用的隨機字元串生成技巧,具有一定參考借鑒價值,需要的朋友可以參考下
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import string
#第一種方法
seed = "!@#$%^&*()_+=-"
sa = []
for i in range(8):
sa.append(random.choice(seed))
salt = '.join(sa)
print salt
#運行結果:l7VSbNEG
#第二種方法
salt = '.join(random.sample(string.ascii_letters + string.digits, 8))
print salt
#運行結果:VOuCtHZs
生成隨機字元串
在加密用戶密碼的時候,一個好方法就是產生一個隨機字元串,然後再和密碼進行混合求摘要。產生隨機字元串的方法找到了這些。
第一種比較簡單,易於理解
第二種不好理解,但很簡潔
本來我只想隨機取四個數字的,用的random.randint(1000,9999)。但是這個開頭不會出現0,有點不爽,後來找到這個文章。