1.异常
try:
尝试执行的代码
except:
出现错误的处理
try:
num = int(input('请输入一个数字:'))
except:
print('请输入正确的整数')
需求:
1.提示用户输入一个整数
2.使用8来除以用户输入的数
try:
尝试执行的代码
except: 错误类型1
出现错误1的处理
except: 错误类型2
出现错误2的处理方式
try:
num = int(input('请输入一个数字:'))
result = 8 / num
print(result)
except ValueError:
print('输入的值不是合法的整数')
except ZeroDivisionError:
print('0不能作除数')
except Exception as r:
print('未知错误 %s' %(r))
finally:
print('~~~~~~~~~~~~~~')
2.主动抛出异常
需求:提示用户输入密码 如果长度小于8位,就抛出异常
def input_passwd():
pwd = input('请输入密码:')
if len(pwd) >= 8:
return pwd
print('主动抛出异常')
ex = Exception('密码长度不足!')
raise ex
try:
print(input_passwd())
except Exception as r:
print(r)
3.paramiko远程密码连接
#基于ssh用于连接远程服务器做操作:
#远程执行命令
#上传/下载文件
import paramiko
client = paramiko.SSHClient() #创建一个SSH连接对象
"""
host
"""
client.set_missing_host_key_policy( #自动选择yes
client.connect( #连接服务器
hostname='172.25.0.1',
username='root',
password='redhat'
)
#执行操作
#标准输入 标准输出 标准错误
stdin,stdout,stderr = client.exec_command('hostname') #命令
#获取命令的执行结果
print(stdout.read().decode('utf-8'))
关闭连接
client.close()
4.paramiko批量连接主机
from paramiko.ssh_exception import NovalidConnect ...
def connect(cmd,hostname,user,password):
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAdd ...
try:
client.connect(
hostname=hostname,
username=user,
password=password
)
except NoValidConnectionsError as e:
return '主机%s连接失败' %(hostname) ...
...