4 min read

【PYTHON脚本分享】利用conoha的API快速自动创建VPS并搭建SS(带界面)

环境:WIN7_64/PYTHON3.5

参数里面的帐号信息需要自己设置。 API用户名,密码,tenantId

下面是脚本源码:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

from tkinter import *  
import requests
import time
import paramiko				#SSS登录
from PIL import Image, ImageTk  		#图形库
import qrcode				#二维码
import base64

#需要python3.5环境。上面的模块直接pip install 安装



################################################################################
#参数
################################################################################

#API用户帐号.后台API。查看帐号信息
user_json ={"auth": {"passwordCredentials": {"username": "gncu00000000","password": "Wdf00wjewefo."},"tenantId":"33bd9e8802394810a9ba85257f55a7e7"}}
#tenant_id
tenant_id = '33bd9e8802394810a9ba85257f55a7e7'
#创建的VPS的root默认密码
vps_root_usr = 'root'
vps_root_pwd = 'Sdf#3_fah23rm@fakn#'
#vps_tag_name
vps_tag_name = 'my-auto-ss'
vps_memory = 'g-1gb'
vps_image  = 'vmi-ubuntu-14.04-amd64'

#SS一键安装命令
ss_install_cmd = 'apt-get -y update && apt-get -y install python-pip && pip install shadowsocks '
ss_install_cmd += '&& sudo ssserver -p 443 -k p3a.s+s.w1324o.rd -m rc4-md5 --user nobody -d start'
ss_install_cmd += '&&echo "\nssok"'
#ss_install_cmd ='ls / &&echo "\nssok" '

#=====================自动获取的全局变量
#X-Auth-Token 登录成功后自动获取
#x_auth_token = ''
token_header = {}				#{'X-Auth-Token': x_auth_token}
vps_json = {}					#{"server": {"adminPass": "7AwxbUP6M4,R","imageRef": "e2b62c96-abbc-41ae-a5f2-b0fe514b755c","flavorRef": "294639c7-72ba-43a5-8ff2-513c8995b869"}}
vps_id = ''
vps_ip = ''
vps_ssh_duankou = 22

#====================请求地址
#帐号验证地址
tokens_url = 'https://identity.tyo1.conoha.io/v2.0/tokens'
#获取帐号信息余额
yu_e_url = 'https://account.tyo1.conoha.io/v1/'+tenant_id+'/payment-summary'
#服务器操作
server_url = 'https://compute.tyo1.conoha.io/v2/'+tenant_id+'/servers'
#获取VPS型号
flavors_url = 'https://compute.tyo1.conoha.io/v2/'+tenant_id+'/flavors'
#获取镜像列表
images_url = 'https://image-service.tyo1.conoha.io/v2/images'


################################################################################
#函数
################################################################################

#====================函数
def post_json_to_url(myurl, myjson):
	r = requests.post(myurl , headers=token_header,json=myjson ,allow_redirects = False )
	return r

#访问链接,返回结果
def get_con_from_url(myurl): 
	r = requests.get(myurl ,headers=token_header ,allow_redirects = False )
	return r


#帐号登录
def login():
	res = post_json_to_url(tokens_url,user_json).json()

	if 'access' in res:
		show_txt('登录成功\n')
		global token_header
		#x_auth_token = res['access']['token']['id']
		token_header = {'X-Auth-Token': res['access']['token']['id']}
	else:
		show_txt('登录失败!程序终止!\n')
		

def chaxun_yu_e():
	res1_josn = get_con_from_url(yu_e_url).json()
	show_txt( '【 ' + str(res1_josn['payment_summary']['total_deposit_amount']) + ' 】日元\n')


def creat_vps():
	#获取flavors_id
	tmp_vps_flavors_id = ''
	res = get_con_from_url( flavors_url ).json()
	for x in res['flavors']:
		#show_txt(x['name'])
		if x['name']== vps_memory:
			tmp_vps_flavors_id = x['id']
	#show_txt('flavors_id:'+tmp_vps_flavors_id)

	#获取images_id
	tmp_vps_images_id =''
	res1 = get_con_from_url( images_url ).json()
	for y in res1['images']:
		#show_txt(y['name'])
		if y['name'] == vps_image:
			tmp_vps_images_id = y['id']
	#show_txt('images_id:'+tmp_vps_images_id)

	#show_txt('开始创建VPS')
	global vps_json
	vps_json = {"server": {"adminPass": vps_root_pwd ,"imageRef": tmp_vps_images_id,"flavorRef": tmp_vps_flavors_id,"metadata": {"instance_name_tag": vps_tag_name},"security_groups":[{"name": "gncs-ipv4-all"}]}}

	res3 = post_json_to_url( server_url ,vps_json)
	#show_txt(res3.status_code)

	if res3.status_code == 202:
		show_txt('创建成功\n')
		global vps_id
		res3_json = res3.json()
		vps_id = res3_json['server']['id']
		#show_txt('服务器ID:'+ vps_id +'\n')
	else:
		show_txt('创建失败!程序终止\n')
		show_txt(res3.content)


#获取VPS数量
def get_vps_num():
	res = get_con_from_url( server_url ).json()
	show_txt(len(res['servers']))

#获取VPS的IP地址
def get_vps_ip():
	#vps_id = '79c0889a-1a07-45b4-b961-896aa8b51944'
	res = get_con_from_url( server_url + '/' + vps_id +'/ips').json()
	#show_txt(res)
	tmp = ''
	for x in res['addresses']:
		#show_txt(x)
		tmp=x

	#show_txt(tmp)
	tmp_ip=''
	for y in res['addresses'][tmp]:
		#show_txt(y)
		if y['version'] == 4:
			global vps_ip
			vps_ip = y['addr']

	show_txt(vps_ip+'\n')	

#自动安装SS
def install_ss():
	client = paramiko.SSHClient() 
	client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
	client.connect( vps_ip , vps_ssh_duankou , username=vps_root_usr, password=vps_root_pwd, timeout=5) 

	stdin, stdout, stderr = client.exec_command(ss_install_cmd) 
	last_cmd = ''
	for std in stdout.readlines(): 
		last_cmd = std
		#show_txt(std)

	#show_txt(last_cmd)
	if last_cmd == 'ssok\n':
		show_txt('安装成功\n')
	else:
		show_txt('安装失败\n')
	
	client.close()


#生成二维码
#def er_wei_ma():
#	str1 = 'rc4-md5:p3a.s+s.w1324o.rd@'+vps_ip+':443'
#	new_str = 'ss://'+base64.b64encode(bytes(str1, "utf-8")).decode()
#	img = qrcode.make(str(new_str))
#	img.save('vps.png')
#	show_txt('vps.png')
#	show_txt('Good Luck!\n')

#生成二维码
def er_wei_ma_new():
	str1 = 'rc4-md5:p3a.s+s.w1324o.rd@'+vps_ip+':443'
	new_str = 'ss://'+base64.b64encode(bytes(str1, "utf-8")).decode()
	img = qrcode.make(str(new_str))
	#img = Image.open("test.jpg")
	img = img.resize((250, 250), Image.ANTIALIAS)  #修改图片大小
	photo = ImageTk.PhotoImage(img)
	qrcode_box.configure(image = photo)
	qrcode_box.image = photo
	show_txt('OK!\n')

#删除VPS
def del_vps():
	#获取VPS的ID
	res = get_con_from_url( server_url +'/detail').json()

	if len(res['servers']) >= 1:
		tmp_id = ''
		del_list = [];
		for x in res['servers']:
			if x['metadata']['instance_name_tag'] == vps_tag_name:
				del_list.append(x['id'])
			#show_txt('name=' +x['metadata']['instance_name_tag']+ '\n')
			#tmp_id = x['id']

		show_txt('自动创建的VPS数量:'+str(len(del_list)) +'台\n' )

		for y in del_list:
			res1 = requests.delete( server_url + '/' + y , headers=token_header)
			if res1.status_code == 204:
				show_txt(y+' - 删除成功!\n')
			else:
				show_txt(y+' - 删除失败!\n')
				show_txt(res1.content)
	else:
		show_txt('没有VPS可以删除!\n')

def patch_crypto_be_discovery():

	"""
	Monkey patches cryptography's backend detection.
	Objective: support pyinstaller freezing.
	"""

	from cryptography.hazmat import backends

	try:
		from cryptography.hazmat.backends.commoncrypto.backend import backend as be_cc
	except ImportError:
		be_cc = None

	try:
		from cryptography.hazmat.backends.openssl.backend import backend as be_ossl
	except ImportError:
		be_ossl = None

	backends._available_backends_list = [
		be for be in (be_cc, be_ossl) if be is not None
	]

#查询余额
def button1():
	clear_txt()
	#查询余额和VPS数量
	show_txt('\n=============查询余额和VPS数量===================\n')
	show_txt('开始登录......')
	res_json = login()
	show_txt('开始查询余额........')
	chaxun_yu_e()
	show_txt('开始查询VPS数量........')
	get_vps_num()
	#input("\n\n\n【按回车继续操作】")



def button2():
	clear_txt()
	show_txt('\n=================一键部署SS=====================\n')
	show_txt('开始登录......')
	res_json = login()
	show_txt('开始创建VPS....')
	creat_vps()
	show_txt('等待15秒...\n')
	time.sleep(15)
	show_txt('获取VPS的IP.......')
	get_vps_ip()
	show_txt('等待60秒...\n')
	time.sleep(60)
	show_txt('安装SS(大概30秒)...........')
	install_ss()
	show_txt('生成二维码.......')
	er_wei_ma_new()
	#input("\n\n\n【按回车继续操作】")

def button3():
	clear_txt()
	show_txt('\n===============删除自动创建的VPS=================\n')
	show_txt('开始登录......')
	res_json = login()
	show_txt('删除VPS......\n')
	del_vps()
	#input("\n\n\n【按回车继续操作】")

#输出显示到TEXT框
def show_txt(str1):
	text_box.insert(INSERT, str1)
	text_box.update()  #更新控件

#清空txt
def clear_txt():
	text_box.delete('1.0',END)
	text_box.update()  #更新控件

########################################
#线程
########################################



################################################################################
#GUI
################################################################################
root=Tk();
root.title("小毛一键SS部署脚本by[conoha.jp]")  
root['width']=650;root['height']=320  #窗口宽度高度  
#root.minsize(650,320);root.maxsize(650,320) #固定窗口大小
root.resizable(False, False)	#禁止缩放


Button(root,text="查询余额&服务器数量",width=20,command=button1).place(x=30,y=30)  
Button(root,text="一键部署SS",width=10,command=button2).place(x=180,y=30) 
Button(root,text="删除自动创建的VPS",width=15,command=button3).place(x=260,y=30)   
text_box = Text(root,width=49,height=16)
text_box.place(x=30,y=80)

Label(root,text="↓↓ 二维码 ↓↓",width=12).place(x=460,y=30)

img = Image.open("none.jpg")
photo = ImageTk.PhotoImage(img)

qrcode_box = Label(root,width=210,height=210,image=photo)
qrcode_box.place(x=400,y=80)


if __name__ == '__main__':

	patch_crypto_be_discovery()
	root.mainloop()