使用C和Shell实现远程Tomcat的重启备份脚本
下面是客户端程序
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#define SERVPORT 6666
#define MAXDATASIZE 1024
#define SERVER_IP "10.10.10.158"
int main(int argc, char* argv[]) {
int sockfd, recvbytes;
char buf[MAXDATASIZE];
struct hostent *host;
char buffer[MAXDATASIZE];
struct sockaddr_in serv_addr;
char name[100];
printf("请输入要操作的tomcat路径\n");
scanf("%s",&name);
while(1){
bzero(buffer, MAXDATASIZE);
if (( sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket error!");
exit(1);
}
bzero(&serv_addr,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(SERVPORT);
serv_addr.sin_addr.s_addr= inet_addr(SERVER_IP);
if (connect(sockfd, (struct sockaddr *)&serv_addr,sizeof(struct sockaddr)) == -1) {
perror("connect error!");
exit(1);
}
printf("请输入要执行的命令:\n");
scanf("%s",&buf);
if(strcmp(buf,"close")==0){
close(sockfd);
return 0;
}
strcat(buffer,name);
strcat(buffer," ");
strcat(buffer,buf);
write(sockfd,buffer, sizeof(buffer));
if ((recvbytes = recv(sockfd, buf, MAXDATASIZE,0)) == -1) {
perror("recv error!");
exit(1);
}
buf[recvbytes] = '\0';
printf("客户端返回的消息:\n %s",buf);
}
close(sockfd);
return 0;
}
下面是服务端程序
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#define SERVPORT 6666
#define BACKLOG 10
#define MAXSIZE 1024
int main() {
int sockfd,client_fd;
struct sockaddr_in my_addr;
struct sockaddr_in remote_addr;
FILE * fp;
char buffer[80];
//创建套接字
if ((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1) {
perror("socket create failed!");
exit(1);
}
//绑定端口地址
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(SERVPORT);
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(my_addr.sin_zero),8);
if (bind(sockfd, (struct sockaddr*)&my_addr, sizeof(struct sockaddr)) == -1) {
perror("bind error!");
exit(1);
}
if (listen(sockfd, BACKLOG) == -1) {
perror("listen error");
exit(1);
}
while (1) {
int sin_size = sizeof(struct sockaddr_in);
char shell[100] =" ";
if ((client_fd = accept(sockfd, (struct sockaddr*)&remote_addr,&sin_size)) == -1) {
perror("accept error!");
continue;
}
printf("Received a connection from %s\n", (char*)inet_ntoa(remote_addr.sin_addr));
if (!fork()) {
int rval;
char buf[MAXSIZE];
if ((rval = read(client_fd, buf, MAXSIZE)) < 0) {
perror("reading stream error!");
continue;
}
printf("客户端发送的消息%s\n",buf);
strcat(shell,"/home/shell/tomcat_online.sh");
strcat(shell," ");
strcat(shell,buf);
fp=popen(shell,"r");
while(fgets(buf,sizeof(buf),fp) != NULL )
{
strcat(buf,"\n");
if (send(client_fd,buf,strlen(buf),0) == -1) perror("send error!");
}
pclose(fp);