常用脚本记录
文章目录
1. shell脚本
1.1 backup.sh // 目录备份(数据备份)
该脚本将/data目录备份到/backup目录下,并以当前时间为文件名进行压缩。同时,该脚本会删除7天前的备份文件。可以使用crontab命令将该脚本设置为定时任务,例如每天凌晨3点执行一次备份:
0 3 * * * /xx/xx/backup_script.sh
#!/bin/bash# 定义备份目录和备份文件名
backup_dir="/backup"
backup_file="data_backup_$(date +%Y%m%d%H%M%S).tar.gz"# 定义要备份的目录
backup_source="/data"# 创建备份目录
if [ -d $backup_dir ]; thenecho "存在目录$backup_dir"
elsemkdir -p $backup_dir
fi# 执行备份
tar -czf $backup_dir/$backup_file $backup_source 2>/dev/null# 删除7天前的备份文件
find $backup_dir -name "data_backup_*" -type f -mtime +7 -exec rm {} \\;
1.2 check_ip.sh // 检查ip
for i in `cat ip`
doif ping -c 1 $i &>/dev/null; thenecho -n $i && echo -e \\\\t "\\033[32m connect success \\033[0m"elseecho -n $i && echo -e \\\\t "\\033[31m connect failed \\033[0m"fi
done
1.3 FlotMonitor.sh // 流量监控
该脚本使用 ifconfig 命令获取 eth0 网络接口的接收和发送流量,并将其转换为千字节(KB)。然后,该脚本输出当前时间和接收/发送流量,并等待指定时间后再次获取流量数据。
#!/bin/bash# 设置监控间隔(秒)
INTERVAL=5while true
do# 获取当前时间now=$(date +"%T")# 使用 ifconfig 命令获取 eth0 网络接口的接收和发送流量rx=$(ifconfig eth0 | grep 'RX packets' | awk '{print $5}')tx=$(ifconfig eth0 | grep 'TX packets' | awk '{print $5}')# 将字节转换成千字节rxk=$(echo "scale=2;$rx/1024"|bc)txk=$(echo "scale=2;$tx/1024"|bc)# 输出当前时间和接收/发送流量echo "$now RX: $rxk KB/s TX: $txk KB/s"# 等待指定时间sleep $INTERVAL
done
1.4 ssh_NoPasswd.sh // 集群免密
#!/bin/bashSSH='/root/.ssh'if [ ! -d $SSH ];thenmkdir -p $SSHchmod 700 $SSH
fiif [ ! -e $SSH/id_rsa.pub ];thenssh-keygen -t rsa -f /root/.ssh/id_rsa -P ''
fiif [ -f $SSH/authorized_keys ];thencat $SSH/id_rsa.pub >> $SSH/authorized_keys
elsetouch $SSH/authorized_keyschmod 600 $SSH/authorized_keyscat $SSH/id_rsa.pub >> $SSH/authorized_keys
fiif [ ! -e cluster_ip ];thencurl xxx >> /root/cluster_ip
elsefor i in cluster_ipdosshpass -pxxx ssh-copy-id -i /root/.ssh/authorized_keys -f -p22 $idone
fi
2. python脚本
2.1 游戏脚本
2.1.1 saolei.py // 扫雷(python3)
import randomclass Minesweeper:def __init__(self, width, height, num_mines):self.width = widthself.height = heightself.num_mines = num_minesself.board = [[0 for x in range(width)] for y in range(height)]self.visible = [[False for x in range(width)] for y in range(height)]self.game_over = False#布雷mines = random.sample(range(width*height), num_mines)for i in mines:row = i // widthcol = i % widthself.board[row][col] = '*'for r in range(row-1, row+2):for c in range(col-1, col+2):if (r >= 0 and r < height and c >= 0 and c < width and self.board[r][c] != '*'):self.board[r][c] += 1#打印棋盘def __str__(self):result = ''for row in range(self.height):for col in range(self.width):if (self.game_over or self.visible[row][col]):result += str(self.board[row][col]) + ' 'else:result += '- 'result += '\\n'return result#翻开格子def reveal(self, row, col):if (self.board[row][col] == '*'):self.game_over = Trueelif (self.visible[row][col] == False):self.visible[row][col] = Trueif (self.board[row][col] == 0):for r in range(row-1, row+2):for c in range(col-1, col+2):if (r >= 0 and r < self.height and c >= 0 and c < self.width):self.reveal(r, c)#判断游戏是否结束def is_game_over(self):return self.game_over or self.is_game_won()#判断游戏是否胜利def is_game_won(self):for row in range(self.height):for col in range(self.width):if (self.board[row][col] != '*' and self.visible[row][col] == False):return Falsereturn True#测试代码
game = Minesweeper(8, 8, 10)while (not game.is_game_over()):print(game)row = int(input('Enter 横坐标: '))col = int(input('Enter 纵坐标: '))game.reveal(row, col)print(game)if (game.is_game_won()):print('You won!')
else:print('Game over!')
2.1.2 Guessnum.py // 猜数字(python3)
import randomdef guess_number():number = random.randint(1, 100)guess = int(input("猜一个1-100之间的数字:"))tries = 1while guess != number:if guess > number:print("太大了,请再试一次。")else:print("太小了,请再试一次。")guess = int(input("再猜一个数字:"))tries += 1print("恭喜,你猜对了!你用了 %d 次猜中了数字 %d。" % (tries, number))guess_number()
2.1.3 DodgeBall.py // 躲避障碍物
import pygame
import random
import sys# 初始化Pygame
pygame.init()# 设置游戏窗口大小
size = (800, 600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("小球躲避障碍物")# 定义颜色
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)# 定义小球
class Ball():def __init__(self, x, y, radius, color):self.x = xself.y = yself.radius = radiusself.color = colordef draw(self):pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius)# 定义障碍物
class Obstacle():def __init__(self, x, y, width, height, color):self.x = xself.y = yself.width = widthself.height = heightself.color = colorself.speed = 5def draw(self):pygame.draw.rect(screen, self.color, [self.x, self.y, self.width, self.height])def move(self):self.x -= self.speed# 创建小球和障碍物的实例
ball = Ball(100, 300, 20, red)
obstacles = []# 游戏循环
game_over = False
score = 0
font = pygame.font.SysFont(None, 30)while not game_over:for event in pygame.event.get():if event.type == pygame.QUIT:game_over = True# 控制小球if event.type == pygame.KEYDOWN:if event.key == pygame.K_UP:ball.y -= 10elif event.key == pygame.K_DOWN:ball.y += 10# 添加障碍物if len(obstacles) < 10:x = random.randint(800, 1600)y = random.randint(0, 600)width = random.randint(20, 50)height = random.randint(50, 200)color = whiteobstacle = Obstacle(x, y, width, height, color)obstacles.append(obstacle)# 绘制背景screen.fill(black)# 绘制小球ball.draw()# 绘制障碍物for obstacle in obstacles:obstacle.draw()obstacle.move()# 判断小球是否撞到障碍物if ball.x + ball.radius > obstacle.x and ball.x - ball.radius < obstacle.x + obstacle.width and ball.y + ball.radius > obstacle.y and ball.y - ball.radius < obstacle.y + obstacle.height:game_over = True# 判断障碍物是否超出屏幕if obstacle.x < -obstacle.width:obstacles.remove(obstacle)score += 1# 显示得分text = font.render("得分:" + str(score), True, white)screen.blit(text, (10, 10))# 更新屏幕pygame.display.update()# 退出Pygame
pygame.quit()
sys.exit()