Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ctype.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #define LINE_MAX 255
- void print_usage() {
- fprintf(stderr,
- "Usage: <nm_connect> [Options]\n Options:\n\t -l: list "
- "networks\n\t -c: connect <SSID>\n");
- exit(1);
- }
- int run_nm(char *cmd, char lines[][LINE_MAX])
- {
- FILE *nm;
- char buffer[LINE_MAX];
- int cnt = 0;
- if ((nm = popen(cmd, "r")) == NULL)
- perror("popen error ....");
- while (fgets(buffer, sizeof(buffer), nm) != NULL) {
- strtok(buffer, "\n");
- strcpy(lines[cnt++], buffer);
- }
- pclose(nm);
- return cnt;
- }
- void connect(char *ssid, char *pass)
- {
- char nmcli[] = "nmcli device wifi";
- char command[256];
- sprintf(command, "%s connect %s password %s", nmcli, ssid, pass);
- int statusCode = system(command);
- if (statusCode == 0) {
- fprintf(stdout, "connected on %s wifi ssid\n", ssid);
- } else {
- fprintf(stderr, "nmcli command error...");
- }
- }
- int main(int argc, char *argv[])
- {
- int option;
- char ssid[15];
- char pass[10];
- int lflag = 0;
- int cflag = 0;
- char out[100][LINE_MAX];
- char comm_nm[LINE_MAX] = "nmcli device wifi";
- char cmd[LINE_MAX];
- if (argc < 2) {
- print_usage();
- }
- while ((option = getopt(argc, argv, "lhc:")) != -1) {
- switch (option) {
- case 'l':
- if (lflag) {
- print_usage();
- } else {
- lflag = 1;
- }
- sprintf(cmd, "%s list", comm_nm);
- int a = run_nm(cmd, out);
- printf("\n%55s\n\n", "Available WIFI Networks");
- for (int i = 0; i < a; ++i)
- printf("%s\n", out[i]);
- exit(EXIT_SUCCESS);
- case 'c':
- if (cflag) {
- print_usage();
- } else {
- cflag = 1;
- }
- strcpy(ssid, optarg);
- strcpy(pass, getpass("password: "));
- connect(ssid, pass);
- exit(EXIT_SUCCESS);
- case 'h':
- print_usage();
- exit(EXIT_SUCCESS);
- default:
- print_usage();
- }
- }
- if (strcmp(argv[optind],"-l") != 0 || strcmp(argv[optind], "-c") != 0 || strcmp(argv[optind], "-h") != 0) {
- fprintf(stderr, "ERROR: Expected options\n");
- puts("");
- print_usage();
- }
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement