好的,下面是一个完整的Python脚本,满足你对传奇游戏服务器管理的需求。这个脚本使用了`psutil`、`smtplib`、`argparse`、`schedule`、`shutil`和`os`库来实现所需的功能。
首先,确保你已经安装了所需的库:
```bash
pipinstallpsutilschedule
```
以下是完整的Python脚本代码:
importos
importshutil
importsmtplib
fromemail.mime.textimportMIMEText
importpsutil
importargparse
importschedule
importtime
importconfigparser
#读取配置文件
config=configparser.ConfigParser()
config.read('server_manager.ini')
#默认配置
DEFAULT_CONFIG={
'email':{
'smtp_server':'smtp.example.com'
'smtp_port':587
'username':'admin@example.com'
'password':'password'
'to_email':'admin@example.com'
}
'monitoring':{
'cpu_threshold':80
'memory_threshold':80
}
'backup':{
'db_name':'game_db'
'db_user':'root'
'db_password':'password'
'backup_dir':'./backups'
'retention_days':7
}
}
#检查并创建默认配置文件
ifnotos.path.exists('server_manager.ini'):
config['email']=DEFAULT_CONFIG['email']
config['monitoring']=DEFAULT_CONFIG['monitoring']
config['backup']=DEFAULT_CONFIG['backup']
withopen('server_manager.ini''w')asconfigfile:
config.write(configfile)
defsend_email(subjectbody):
msg=MIMEText(body)
msg['Subject']=subject
msg['From']=config['email']['username']
msg['To']=config['email']['to_email']
try:
withsmtplib.SMTP(config['email']['smtp_server']int(config['email']['smtp_port']))asserver:
server.starttls()
server.login(config['email']['username']config['email']['password'])
server.sendmail(config['email']['username']config['email']['to_email']msg.as_string())
print(f"Emailsent:{subject}")
exceptExceptionase:
print(f"Failedtosendemail:{e}")
defcheck_system_resources():
cpu_usage=psutil.cpu_percent(interval=1)
memory_usage=psutil.virtual_memory().percent
ifcpu_usage>int(config['monitoring']['cpu_threshold']):
send_email("HighCPUUsageAlert"f"CurrentCPUusageis{cpu_usage}%")
ifmemory_usage>int(config['monitoring']['memory_threshold']):
send_email("HighMemoryUsageAlert"f"CurrentMemoryusageis{memory_usage}%")
defbackup_database():
db_name=config['backup']['db_name']
db_user=config['backup']['db_user']
db_password=config['backup']['db_password']
backup_dir=config['backup']['backup_dir']
retention_days=int(config['backup']['retention_days'])
ifnotos.path.exists(backup_dir):
os.makedirs(backup_dir)
timestamp=time.strftime("%Y%m%d%H%M%S")
backup_file=os.path.join(backup_dirf"{db_name}_{timestamp}.sql")
dump_cmd=f"mysqldump-u{db_user}-p{db_password}{db_name}>{backup_file}"
os.system(dump_cmd)
#清理过期备份
forfileinos.listdir(backup_dir):
file_path=os.path.join(backup_dirfile)
file_time=os.path.getmtime(file_path)
if(time.time()-file_time)//(24*3600)>=retention_days:
os.remove(file_path)
print(f"Databasebackedupto{backup_file}")
defrestart_service():
print("Restartinggameservice...")
#这里可以添加具体的重启命令
#os.system("sudosystemctlrestartgame-server.service")
defmain():
parser=argparse.ArgumentParser(description="ServerManagerforLegendMUDServer")
parser.add_argument('--check-resources'action='store_true'help='Checksystemresources')
parser.add_argument('--backup-db'action='store_true'help='Backupdatabase')
parser.add_argument('--restart-service'action='store_true'help='Restartgameservice')
args=parser.parse_args()
ifargs.check_resources:
check_system_resources()
elifargs.backup_db:
backup_database()
elifargs.restart_service:
restart_service()
else:
print("Nocommandspecified.Use--helpformoreinformation.")
#定时任务
schedule.every().day.at("00:00").do(backup_database)
whileTrue:
schedule.run_pending()
time.sleep(1)
if__name__=="__main__":
main()
###配置文件`server_manager.ini`
在项目目录下创建一个名为`server_manager.ini`的配置文件,并根据实际情况修改以下内容:
```ini
[email]
smtp_server=smtp.example.com
smtp_port=587
username=admin@example.com
password=password
to_email=admin@example.com
[monitoring]
cpu_threshold=80
memory_threshold=80
[backup]
db_name=game_db
db_user=root
db_password=password
backup_dir=./backups
retention_days=7
```
###使用说明
1.**检查系统资源**:
```bash
pythonserver_manager.py--check-resources
```
2.**备份数据库**:
```bash
pythonserver_manager.py--backup-db
```
3.**重启服务**:
```bash
pythonserver_manager.py--restart-service
```
4.**运行定时任务**:
直接运行脚本即可启动定时任务:
```bash
pythonserver_manager.py
```
###注意事项
1.**安全性**:确保你的配置文件和敏感信息(如密码)安全存储。
2.**权限**:根据需要调整脚本的执行权限,特别是涉及数据库备份和重启服务的操作。
3.**依赖项**:确保所有依赖项已正确安装,并且MySQL客户端工具已安装以便进行数据库备份。
希望这个脚本能帮助你更好地管理和维护传奇游戏服务器!如果有任何问题或需要进一步的帮助,请告诉我。
首先,确保你已经安装了所需的库:
```bash
pipinstallpsutilschedule
```
以下是完整的Python脚本代码:
importos
importshutil
importsmtplib
fromemail.mime.textimportMIMEText
importpsutil
importargparse
importschedule
importtime
importconfigparser
#读取配置文件
config=configparser.ConfigParser()
config.read('server_manager.ini')
#默认配置
DEFAULT_CONFIG={
'email':{
'smtp_server':'smtp.example.com'
'smtp_port':587
'username':'admin@example.com'
'password':'password'
'to_email':'admin@example.com'
}
'monitoring':{
'cpu_threshold':80
'memory_threshold':80
}
'backup':{
'db_name':'game_db'
'db_user':'root'
'db_password':'password'
'backup_dir':'./backups'
'retention_days':7
}
}
#检查并创建默认配置文件
ifnotos.path.exists('server_manager.ini'):
config['email']=DEFAULT_CONFIG['email']
config['monitoring']=DEFAULT_CONFIG['monitoring']
config['backup']=DEFAULT_CONFIG['backup']
withopen('server_manager.ini''w')asconfigfile:
config.write(configfile)
defsend_email(subjectbody):
msg=MIMEText(body)
msg['Subject']=subject
msg['From']=config['email']['username']
msg['To']=config['email']['to_email']
try:
withsmtplib.SMTP(config['email']['smtp_server']int(config['email']['smtp_port']))asserver:
server.starttls()
server.login(config['email']['username']config['email']['password'])
server.sendmail(config['email']['username']config['email']['to_email']msg.as_string())
print(f"Emailsent:{subject}")
exceptExceptionase:
print(f"Failedtosendemail:{e}")
defcheck_system_resources():
cpu_usage=psutil.cpu_percent(interval=1)
memory_usage=psutil.virtual_memory().percent
ifcpu_usage>int(config['monitoring']['cpu_threshold']):
send_email("HighCPUUsageAlert"f"CurrentCPUusageis{cpu_usage}%")
ifmemory_usage>int(config['monitoring']['memory_threshold']):
send_email("HighMemoryUsageAlert"f"CurrentMemoryusageis{memory_usage}%")
defbackup_database():
db_name=config['backup']['db_name']
db_user=config['backup']['db_user']
db_password=config['backup']['db_password']
backup_dir=config['backup']['backup_dir']
retention_days=int(config['backup']['retention_days'])
ifnotos.path.exists(backup_dir):
os.makedirs(backup_dir)
timestamp=time.strftime("%Y%m%d%H%M%S")
backup_file=os.path.join(backup_dirf"{db_name}_{timestamp}.sql")
dump_cmd=f"mysqldump-u{db_user}-p{db_password}{db_name}>{backup_file}"
os.system(dump_cmd)
#清理过期备份
forfileinos.listdir(backup_dir):
file_path=os.path.join(backup_dirfile)
file_time=os.path.getmtime(file_path)
if(time.time()-file_time)//(24*3600)>=retention_days:
os.remove(file_path)
print(f"Databasebackedupto{backup_file}")
defrestart_service():
print("Restartinggameservice...")
#这里可以添加具体的重启命令
#os.system("sudosystemctlrestartgame-server.service")
defmain():
parser=argparse.ArgumentParser(description="ServerManagerforLegendMUDServer")
parser.add_argument('--check-resources'action='store_true'help='Checksystemresources')
parser.add_argument('--backup-db'action='store_true'help='Backupdatabase')
parser.add_argument('--restart-service'action='store_true'help='Restartgameservice')
args=parser.parse_args()
ifargs.check_resources:
check_system_resources()
elifargs.backup_db:
backup_database()
elifargs.restart_service:
restart_service()
else:
print("Nocommandspecified.Use--helpformoreinformation.")
#定时任务
schedule.every().day.at("00:00").do(backup_database)
whileTrue:
schedule.run_pending()
time.sleep(1)
if__name__=="__main__":
main()
###配置文件`server_manager.ini`
在项目目录下创建一个名为`server_manager.ini`的配置文件,并根据实际情况修改以下内容:
```ini
[email]
smtp_server=smtp.example.com
smtp_port=587
username=admin@example.com
password=password
to_email=admin@example.com
[monitoring]
cpu_threshold=80
memory_threshold=80
[backup]
db_name=game_db
db_user=root
db_password=password
backup_dir=./backups
retention_days=7
```
###使用说明
1.**检查系统资源**:
```bash
pythonserver_manager.py--check-resources
```
2.**备份数据库**:
```bash
pythonserver_manager.py--backup-db
```
3.**重启服务**:
```bash
pythonserver_manager.py--restart-service
```
4.**运行定时任务**:
直接运行脚本即可启动定时任务:
```bash
pythonserver_manager.py
```
###注意事项
1.**安全性**:确保你的配置文件和敏感信息(如密码)安全存储。
2.**权限**:根据需要调整脚本的执行权限,特别是涉及数据库备份和重启服务的操作。
3.**依赖项**:确保所有依赖项已正确安装,并且MySQL客户端工具已安装以便进行数据库备份。
希望这个脚本能帮助你更好地管理和维护传奇游戏服务器!如果有任何问题或需要进一步的帮助,请告诉我。

