#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <signal.h>
using namespace std;
class Rec
{
public:
int socketfd ;
int acceptfd ;
int len ;
int pid ;
int init(char buf[255], int buf_len)
{
socketfd = socket(AF_INET, SOCK_STREAM, 0);
if (socketfd == -1)
perror("socket error");
else
{
struct sockaddr_in s_addr;
s_addr.sin_family = AF_INET;
s_addr.sin_addr.s_addr = INADDR_ANY;
s_addr.sin_port = htons(12345);
len = sizeof(s_addr);
int res = bind(socketfd, (struct sockaddr *)&s_addr, len);
if (res == -1)
perror("bind error");
else
{
if (listen(socketfd, 2) == -1)
perror("listen error");
cout << "等待客户端上线" << endl;
pid = fork();
if (pid == 0){
acceptfd = accept(socketfd, NULL, NULL);
cout << "客户端上线" << endl;
while(1)
{
int err = read(acceptfd, buf, buf_len);
if ((strncmp(buf, "quit", 4) == 0) or (err == 0) )
{
cout << "read err" << err << endl;
close(acceptfd);
close(socketfd);
return -1;
}
cout << "pid = " << getpid() << " 说: " << buf << endl;
}
}
}
}
}
};
class Send
{
public:
int socketfd;
int len;
void init()
{
socketfd = socket(AF_INET, SOCK_STREAM, 0);
if (socketfd == -1)
perror("socket error");
else
{
struct sockaddr_in s_addr;
s_addr.sin_family = AF_INET;
s_addr.sin_addr.s_addr = inet_addr("192.168.0.251");
s_addr.sin_port = htons(12345);
len = sizeof(s_addr);
int res = connect(socketfd, (struct sockaddr*)&s_addr, len);
while (res == -1)
{
sleep(1);
perror("connect error");
res = connect(socketfd, (struct sockaddr*)&s_addr, len);
}
}
}
int sendmsg(char buf[255], int buf_len)
{
fgets(buf, buf_len, stdin);
write(socketfd, buf, buf_len);
if ((strncmp(buf, "quit", 4) == 0) )
{
sleep(3);
close(socketfd);
return -1;
}
}
};
int main()
{
char buf[255] = { 0 };
Rec Recinst;
Send Sendinst;
Recinst.init(buf, sizeof(buf));
Sendinst.init();
while(1){
if(Sendinst.sendmsg(buf, sizeof(buf)) == -1)
{
kill(Recinst.pid,SIGKILL);
return -1;
}
}
}
buid.sh
#!/bin/bash
g++ ser.cpp -o ser
g++ ser2.cpp -o ser2
./kill.sh
kill.sh
#!/bin/bash
kill_list=("cl" "ser" "ser2")
for pro in ${kill_list[@]}
do
echo $pro "killed"
ps -ef |grep -w $pro |grep -v grep |awk '{print $2}' |xargs kill -9 >& /dev/null
done
scp.sh
#!/bin/bash
scp -r $* root@192.168.0.251:/root/day/
pssh.sh
#!/bin/bash
dir=`pwd`
pssh -H 192.168.0.251 -l root -i cd $dir; $*
$*
使用说明
本机使用:
1、cp -rf ser.cpp ser2cpp 2、ser2.cpp rec_port = ser.cpp send_port 3、ser2.cpp send_port = ser.cpp rec_port
双机使用:
1、ser.cpp copy到多机; 2、修改ip地址为目标机器Ip; 3、端口改为一样;
永久关闭防火墙步骤
1、移除防火墙服务
systemctl disable firewalld
2、启动停止防火墙服务
systemctl stop firewalld
3、关闭权限
vi /etc/selinux/config
SELINUX=disabled
关闭网卡,慎用
systemctl stop nework
|