/* Main program Queries various SNMP values on cisco devices. */ int main(int argc, char *argv[]) { char* output; struct snmp_session session; char arg; // int i; // long snmpVer; /* Initialize and build snmp session, add version, community, host, etc */ init_snmp("Linux_checks"); snmp_sess_init( &session ); switch (arg = snmp_parse_args(argc, argv, &session, "C:", optProc)) { case -3: exit(1); case -2: exit(0); case -1: usage(); exit(1); default: break; } /* Check warning/critical test values to verify they are within the appropriate ranges */ if ((crit > 100) && (strcmp(mode, "sessions"))) { printf("Critical threshold should be less than 100!\n"); usage(); exit(RESULT_UNKNOWN); } else if (crit < 0) { printf("Critical threshould must be greater than 0!\n"); usage(); exit(RESULT_UNKNOWN); } else if ((warn < 0) && (strcmp(mode, "sessions"))) { printf("Warning threshold must be greater than or equal to 0!\n"); usage(); exit(RESULT_UNKNOWN); } else if (warn > crit) { printf("Warning threshold must not be greater than critical threshold!\n"); usage(); exit(RESULT_UNKNOWN); } output = checkCPU(&session); printf("%s", output); return exitVal; }
void snmpd_parse_config_trapsess(const char *word, char *cptr) { char *argv[MAX_ARGS], *cp = cptr, tmp[SPRINT_MAX_LEN]; int argn, arg; netsnmp_session session, *ss; /* * inform or trap? default to trap */ traptype = SNMP_MSG_TRAP2; /* * create the argv[] like array */ argv[0] = strdup("snmpd-trapsess"); /* bogus entry for getopt() */ for (argn = 1; cp && argn < MAX_ARGS; argn++) { cp = copy_nword(cp, tmp, SPRINT_MAX_LEN); argv[argn] = strdup(tmp); } arg = snmp_parse_args(argn, argv, &session, "C:", trapOptProc); ss = snmp_open(&session); for (; argn > 0; argn--) { free(argv[argn - 1]); } if (!ss) { config_perror ("snmpd: failed to parse this line or the remote trap receiver is down. Possible cause:"); snmp_sess_perror("snmpd: snmpd_parse_config_trapsess()", &session); return; } #ifndef DISABLE_SNMPV1 if (ss->version == SNMP_VERSION_1) { add_trap_session(ss, SNMP_MSG_TRAP, 0, SNMP_VERSION_1); } else { #endif add_trap_session(ss, traptype, (traptype == SNMP_MSG_INFORM), ss->version); #ifndef DISABLE_SNMPV1 } #endif }
int main(int argc, char *argv[]) { netsnmp_session session, *ss; netsnmp_pdu *pdu, *response = NULL; netsnmp_variable_list *vars; int arg; int count; int current_name = 0; int current_type = 0; int current_value = 0; char *names[SNMP_MAX_CMDLINE_OIDS]; char types[SNMP_MAX_CMDLINE_OIDS]; char *values[SNMP_MAX_CMDLINE_OIDS]; oid name[MAX_OID_LEN]; size_t name_length; int status; int exitval = 0; putenv(strdup("POSIXLY_CORRECT=1")); /* * get the common command line arguments */ switch (arg = snmp_parse_args(argc, argv, &session, "C:", optProc)) { case -2: exit(0); case -1: usage(); exit(1); default: break; } if (arg >= argc) { fprintf(stderr, "Missing object name\n"); usage(); exit(1); } if ((argc - arg) > 3*SNMP_MAX_CMDLINE_OIDS) { fprintf(stderr, "Too many assignments specified. "); fprintf(stderr, "Only %d allowed in one request.\n", SNMP_MAX_CMDLINE_OIDS); usage(); exit(1); } /* * get object names, types, and values */ for (; arg < argc; arg++) { DEBUGMSGTL(("snmp_parse_args", "handling (#%d): %s %s %s\n", arg,argv[arg], arg+1 < argc ? argv[arg+1] : NULL, arg+2 < argc ? argv[arg+2] : NULL)); names[current_name++] = argv[arg++]; if (arg < argc) { switch (*argv[arg]) { case '=': case 'i': case 'u': case 't': case 'a': case 'o': case 's': case 'x': case 'd': case 'b': #ifdef OPAQUE_SPECIAL_TYPES case 'I': case 'U': case 'F': case 'D': #endif /* OPAQUE_SPECIAL_TYPES */ types[current_type++] = *argv[arg++]; break; default: fprintf(stderr, "%s: Bad object type: %c\n", argv[arg - 1], *argv[arg]); exit(1); } } else { fprintf(stderr, "%s: Needs type and value\n", argv[arg - 1]); exit(1); } if (arg < argc) values[current_value++] = argv[arg]; else { fprintf(stderr, "%s: Needs value\n", argv[arg - 2]); exit(1); } } SOCK_STARTUP; /* * open an SNMP session */ ss = snmp_open(&session); if (ss == NULL) { /* * diagnose snmp_open errors with the input netsnmp_session pointer */ snmp_sess_perror("snmpset", &session); SOCK_CLEANUP; exit(1); } /* * create PDU for SET request and add object names and values to request */ pdu = snmp_pdu_create(SNMP_MSG_SET); for (count = 0; count < current_name; count++) { name_length = MAX_OID_LEN; if (snmp_parse_oid(names[count], name, &name_length) == NULL) { snmp_perror(names[count]); failures++; } else if (snmp_add_var (pdu, name, name_length, types[count], values[count])) { snmp_perror(names[count]); failures++; } } if (failures) { SOCK_CLEANUP; exit(1); } /* * do the request */ status = snmp_synch_response(ss, pdu, &response); if (status == STAT_SUCCESS) { if (response->errstat == SNMP_ERR_NOERROR) { if (!quiet) { for (vars = response->variables; vars; vars = vars->next_variable) print_variable(vars->name, vars->name_length, vars); } } else { fprintf(stderr, "Error in packet.\nReason: %s\n", snmp_errstring(response->errstat)); if (response->errindex != 0) { fprintf(stderr, "Failed object: "); for (count = 1, vars = response->variables; vars && (count != response->errindex); vars = vars->next_variable, count++); if (vars) fprint_objid(stderr, vars->name, vars->name_length); fprintf(stderr, "\n"); } exitval = 2; } } else if (status == STAT_TIMEOUT) { fprintf(stderr, "Timeout: No Response from %s\n", session.peername); exitval = 1; } else { /* status == STAT_ERROR */ snmp_sess_perror("snmpset", ss); exitval = 1; } if (response) snmp_free_pdu(response); snmp_close(ss); SOCK_CLEANUP; return exitval; }
int main(int argc, char *argv[]) { netsnmp_session session; struct protoent *p; char *cp; af = AF_UNSPEC; cp = strrchr( argv[0], '/' ); if (cp) progname = cp+1; else progname = argv[0]; switch (snmp_parse_args( argc, argv, &session, "C:iRs", optProc)) { case NETSNMP_PARSE_ARGS_ERROR: exit(1); case NETSNMP_PARSE_ARGS_SUCCESS_EXIT: exit(0); case NETSNMP_PARSE_ARGS_ERROR_USAGE: usage(); exit(1); default: break; } /* * Check argc vs optind ?? */ argv += optind; argc -= optind; /* * Open an SNMP session. */ SOCK_STARTUP; ss = snmp_open(&session); if (ss == NULL) { /* * diagnose snmp_open errors with the input netsnmp_session pointer */ snmp_sess_perror("snmpnetstat", &session); SOCK_CLEANUP; exit(1); } /* * Omitted: * Privilege handling * "Backward Compatibility" * Kernel namelis handling */ if (mflag) { /* mbpr(nl[N_MBSTAT].n_value, nl[N_MBPOOL].n_value, nl[N_MCLPOOL].n_value); */ exit(0); } if (pflag) { printproto(tp, tp->pr_name); exit(0); } /* * Keep file descriptors open to avoid overhead * of open/close on each call to get* routines. */ sethostent(1); setnetent(1); if (iflag) { intpr(interval); exit(0); } if (rflag) { /* if (sflag) rt_stats(); else */ if (Lflag || routexpr(af) == 0) { if (route4pr(af) == 0 && af == AF_INET) routepr(); route6pr(af); } exit(0); } /* if (gflag) { if (sflag) { if (af == AF_INET || af == AF_UNSPEC) mrt_stats(nl[N_MRTPROTO].n_value, nl[N_MRTSTAT].n_value); #ifdef NETSNMP_ENABLE_IPV6 if (af == AF_INET6 || af == AF_UNSPEC) mrt6_stats(nl[N_MRT6PROTO].n_value, nl[N_MRT6STAT].n_value); #endif } else { if (af == AF_INET || af == AF_UNSPEC) mroutepr(nl[N_MRTPROTO].n_value, nl[N_MFCHASHTBL].n_value, nl[N_MFCHASH].n_value, nl[N_VIFTABLE].n_value); #ifdef NETSNMP_ENABLE_IPV6 if (af == AF_INET6 || af == AF_UNSPEC) mroute6pr(nl[N_MRT6PROTO].n_value, nl[N_MF6CTABLE].n_value, nl[N_MIF6TABLE].n_value); #endif } exit(0); } */ setservent(1); if (af == AF_UNSPEC && Lflag) { setprotoent(1); /* ugh, this is O(MN) ... why do we do this? */ while ((p = getprotoent())) { for (tp = protox; tp->pr_name; tp++) if (strcmp(tp->pr_name, p->p_name) == 0) if (tp->pr_name && tp->pr_wanted) printproto(tp, p->p_name); } endprotoent(); } if (af == AF_UNSPEC && !Lflag) for (tp = ipxprotox; tp->pr_name; tp++) printproto(tp, tp->pr_name); if (af == AF_INET) for (tp = protox; tp->pr_name; tp++) printproto(tp, tp->pr_name); if (af == AF_INET6) for (tp = ip6protox; tp->pr_name; tp++) printproto(tp, tp->pr_name); /* if (af == AF_IPX || af == AF_UNSPEC) for (tp = ipxprotox; tp->pr_name; tp++) printproto(tp, tp->pr_name); if (af == AF_NS || af == AF_UNSPEC) for (tp = nsprotox; tp->pr_name; tp++) printproto(tp, tp->pr_name); if ((af == AF_UNIX || af == AF_UNSPEC) && !sflag) unixpr(nl[N_UNIXSW].n_value); if (af == AF_APPLETALK || af == AF_UNSPEC) for (tp = atalkprotox; tp->pr_name; tp++) printproto(tp, tp->pr_name); */ exit(0); }
int main (int argc, char *argv[]) { netsnmp_session session, *ss; netsnmp_pdu *pdu, *response; oid name[MAX_OID_LEN]; size_t name_length; int arg; int status; char *trap = NULL; char *prognam; int exitval = 0; #ifndef NETSNMP_DISABLE_SNMPV1 char *specific = NULL, *description = NULL, *agent = NULL; in_addr_t *pdu_in_addr_t; #endif prognam = strrchr (argv[0], '/'); if (prognam) prognam++; else prognam = argv[0]; putenv (strdup ("POSIXLY_CORRECT=1")); if (strcmp (prognam, "snmpinform") == 0) inform = 1; switch (arg = snmp_parse_args (argc, argv, &session, "C:", optProc)) { case NETSNMP_PARSE_ARGS_ERROR: exit (1); case NETSNMP_PARSE_ARGS_SUCCESS_EXIT: exit (0); case NETSNMP_PARSE_ARGS_ERROR_USAGE: usage (); exit (1); default: break; } SOCK_STARTUP; session.callback = snmp_input; session.callback_magic = NULL; /* * setup the local engineID which may be for either or both of the * contextEngineID and/or the securityEngineID. */ setup_engineID (NULL, NULL); /* if we don't have a contextEngineID set via command line arguments, use our internal engineID as the context. */ if (session.contextEngineIDLen == 0 || session.contextEngineID == NULL) { session.contextEngineID = snmpv3_generate_engineID (&session.contextEngineIDLen); } if (session.version == SNMP_VERSION_3 && !inform) { /* * for traps, we use ourselves as the authoritative engine * which is really stupid since command line apps don't have a * notion of a persistent engine. Hence, our boots and time * values are probably always really wacked with respect to what * a manager would like to see. * * The following should be enough to: * * 1) prevent the library from doing discovery for engineid & time. * 2) use our engineid instead of the remote engineid for * authoritative & privacy related operations. * 3) The remote engine must be configured with users for our engineID. * * -- Wes */ /* * pick our own engineID */ if (session.securityEngineIDLen == 0 || session.securityEngineID == NULL) { session.securityEngineID = snmpv3_generate_engineID (&session.securityEngineIDLen); } /* * set boots and time, which will cause problems if this * machine ever reboots and a remote trap receiver has cached our * boots and time... I'll cause a not-in-time-window report to * be sent back to this machine. */ if (session.engineBoots == 0) session.engineBoots = 1; if (session.engineTime == 0) /* not really correct, */ session.engineTime = get_uptime (); /* but it'll work. Sort of. */ } ss = snmp_add (&session, netsnmp_transport_open_client ("snmptrap", session.peername), NULL, NULL); if (ss == NULL) { /* * diagnose netsnmp_transport_open_client and snmp_add errors with * the input netsnmp_session pointer */ snmp_sess_perror ("snmptrap", &session); SOCK_CLEANUP; exit (1); } #ifndef NETSNMP_DISABLE_SNMPV1 if (session.version == SNMP_VERSION_1) { if (inform) { fprintf (stderr, "Cannot send INFORM as SNMPv1 PDU\n"); SOCK_CLEANUP; exit (1); } pdu = snmp_pdu_create (SNMP_MSG_TRAP); if (!pdu) { fprintf (stderr, "Failed to create trap PDU\n"); SOCK_CLEANUP; exit (1); } pdu_in_addr_t = (in_addr_t *) pdu->agent_addr; if (arg == argc) { fprintf (stderr, "No enterprise oid\n"); usage (); SOCK_CLEANUP; exit (1); } if (argv[arg][0] == 0) { pdu->enterprise = (oid *) malloc (sizeof (objid_enterprise)); memcpy (pdu->enterprise, objid_enterprise, sizeof (objid_enterprise)); pdu->enterprise_length = sizeof (objid_enterprise) / sizeof (oid); } else { name_length = MAX_OID_LEN; if (!snmp_parse_oid (argv[arg], name, &name_length)) { snmp_perror (argv[arg]); usage (); SOCK_CLEANUP; exit (1); } pdu->enterprise = (oid *) malloc (name_length * sizeof (oid)); memcpy (pdu->enterprise, name, name_length * sizeof (oid)); pdu->enterprise_length = name_length; } if (++arg >= argc) { fprintf (stderr, "Missing agent parameter\n"); usage (); SOCK_CLEANUP; exit (1); } agent = argv[arg]; if (agent != NULL && strlen (agent) != 0) { int ret = netsnmp_gethostbyname_v4 (agent, pdu_in_addr_t); if (ret < 0) { fprintf (stderr, "unknown host: %s\n", agent); exit (1); } } else { *pdu_in_addr_t = get_myaddr (); } if (++arg == argc) { fprintf (stderr, "Missing generic-trap parameter\n"); usage (); SOCK_CLEANUP; exit (1); } trap = argv[arg]; pdu->trap_type = atoi (trap); if (++arg == argc) { fprintf (stderr, "Missing specific-trap parameter\n"); usage (); SOCK_CLEANUP; exit (1); } specific = argv[arg]; pdu->specific_type = atoi (specific); if (++arg == argc) { fprintf (stderr, "Missing uptime parameter\n"); usage (); SOCK_CLEANUP; exit (1); } description = argv[arg]; if (description == NULL || *description == 0) pdu->time = get_uptime (); else pdu->time = atol (description); } else #endif { long sysuptime; char csysuptime[20]; pdu = snmp_pdu_create (inform ? SNMP_MSG_INFORM : SNMP_MSG_TRAP2); if (!pdu) { fprintf (stderr, "Failed to create notification PDU\n"); SOCK_CLEANUP; exit (1); } if (arg == argc) { fprintf (stderr, "Missing up-time parameter\n"); usage (); SOCK_CLEANUP; exit (1); } trap = argv[arg]; if (*trap == 0) { sysuptime = get_uptime (); sprintf (csysuptime, "%ld", sysuptime); trap = csysuptime; } snmp_add_var (pdu, objid_sysuptime, sizeof (objid_sysuptime) / sizeof (oid), 't', trap); if (++arg == argc) { fprintf (stderr, "Missing trap-oid parameter\n"); usage (); SOCK_CLEANUP; exit (1); } if (snmp_add_var (pdu, objid_snmptrap, sizeof (objid_snmptrap) / sizeof (oid), 'o', argv[arg]) != 0) { snmp_perror (argv[arg]); SOCK_CLEANUP; exit (1); } } arg++; while (arg < argc) { arg += 3; if (arg > argc) { fprintf (stderr, "%s: Missing type/value for variable\n", argv[arg - 3]); SOCK_CLEANUP; exit (1); } name_length = MAX_OID_LEN; if (!snmp_parse_oid (argv[arg - 3], name, &name_length)) { snmp_perror (argv[arg - 3]); SOCK_CLEANUP; exit (1); } if (snmp_add_var (pdu, name, name_length, argv[arg - 2][0], argv[arg - 1]) != 0) { snmp_perror (argv[arg - 3]); SOCK_CLEANUP; exit (1); } } if (inform) status = snmp_synch_response (ss, pdu, &response); else status = snmp_send (ss, pdu) == 0; if (status) { snmp_sess_perror (inform ? "snmpinform" : "snmptrap", ss); if (!inform) snmp_free_pdu (pdu); exitval = 1; } else if (inform) snmp_free_pdu (response); snmp_close (ss); snmp_shutdown ("snmpapp"); SOCK_CLEANUP; return exitval; }
int main(int argc, char *argv[]) { netsnmp_session session, *ss; netsnmp_pdu *pdu; netsnmp_pdu *response; netsnmp_variable_list *vars; int arg; int count; int current_name = 0; char *names[128]; oid name[MAX_OID_LEN]; size_t name_length; int status; int exitval = 0; /* * get the common command line arguments */ switch (arg = snmp_parse_args(argc, argv, &session, "C:", optProc)) { case -2: exit(0); case -1: usage(); exit(1); default: break; } if (arg >= argc) { fprintf(stderr, "Missing object name\n"); usage(); exit(1); } /* * get the object names */ for (; arg < argc; arg++) names[current_name++] = argv[arg]; SOCK_STARTUP; /* * Open an SNMP session. */ ss = snmp_open(&session); if (ss == NULL) { /* * diagnose snmp_open errors with the input netsnmp_session pointer */ snmp_sess_perror("snmpget", &session); SOCK_CLEANUP; exit(1); } /* * Create PDU for GET request and add object names to request. */ pdu = snmp_pdu_create(SNMP_MSG_GET); for (count = 0; count < current_name; count++) { name_length = MAX_OID_LEN; if (!snmp_parse_oid(names[count], name, &name_length)) { snmp_perror(names[count]); failures++; } else snmp_add_null_var(pdu, name, name_length); } if (failures) { SOCK_CLEANUP; exit(1); } /* * Perform the request. * * If the Get Request fails, note the OID that caused the error, * "fix" the PDU (removing the error-prone OID) and retry. */ retry: status = snmp_synch_response(ss, pdu, &response); if (status == STAT_SUCCESS) { if (response->errstat == SNMP_ERR_NOERROR) { for (vars = response->variables; vars; vars = vars->next_variable) print_variable(vars->name, vars->name_length, vars); } else { fprintf(stderr, "Error in packet\nReason: %s\n", snmp_errstring(response->errstat)); if (response->errindex != 0) { fprintf(stderr, "Failed object: "); for (count = 1, vars = response->variables; vars && count != response->errindex; vars = vars->next_variable, count++) /*EMPTY*/; if (vars) { fprint_objid(stderr, vars->name, vars->name_length); } fprintf(stderr, "\n"); } exitval = 2; /* * retry if the errored variable was successfully removed */ if (!netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_APP_DONT_FIX_PDUS)) { pdu = snmp_fix_pdu(response, SNMP_MSG_GET); snmp_free_pdu(response); response = NULL; if (pdu != NULL) { goto retry; } } } /* endif -- SNMP_ERR_NOERROR */ } else if (status == STAT_TIMEOUT) { fprintf(stderr, "Timeout: No Response from %s.\n", session.peername); exitval = 1; } else { /* status == STAT_ERROR */ snmp_sess_perror("snmpget", ss); exitval = 1; } /* endif -- STAT_SUCCESS */ if (response) snmp_free_pdu(response); snmp_close(ss); SOCK_CLEANUP; return exitval; } /* end main() */
int main(int argc, char *argv[]) { netsnmp_session session, *ss; netsnmp_pdu *pdu, *response; netsnmp_variable_list *vars; int arg; oid name[MAX_OID_LEN]; size_t name_length; oid root[MAX_OID_LEN]; size_t rootlen; int count; int running; int status; int check; int exitval = 0; netsnmp_ds_register_config(ASN_BOOLEAN, "snmpwalk", "includeRequested", NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_WALK_INCLUDE_REQUESTED); netsnmp_ds_register_config(ASN_BOOLEAN, "snmpwalk", "printStatistics", NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_WALK_PRINT_STATISTICS); netsnmp_ds_register_config(ASN_BOOLEAN, "snmpwalk", "dontCheckOrdering", NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_WALK_DONT_CHECK_LEXICOGRAPHIC); /* * get the common command line arguments */ switch (arg = snmp_parse_args(argc, argv, &session, "C:", optProc)) { case NETSNMP_PARSE_ARGS_ERROR: exit(1); case NETSNMP_PARSE_ARGS_SUCCESS_EXIT: exit(0); case NETSNMP_PARSE_ARGS_ERROR_USAGE: usage(); exit(1); default: break; } /* * get the initial object and subtree */ if (arg < argc) { /* * specified on the command line */ rootlen = MAX_OID_LEN; if (snmp_parse_oid(argv[arg], root, &rootlen) == NULL) { snmp_perror(argv[arg]); exit(1); } } else { /* * use default value */ memmove(root, objid_mib, sizeof(objid_mib)); rootlen = sizeof(objid_mib) / sizeof(oid); } SOCK_STARTUP; /* * open an SNMP session */ ss = snmp_open(&session); if (ss == NULL) { /* * diagnose snmp_open errors with the input netsnmp_session pointer */ snmp_sess_perror("snmpbulkwalk", &session); SOCK_CLEANUP; exit(1); } /* * setup initial object name */ memmove(name, root, rootlen * sizeof(oid)); name_length = rootlen; running = 1; check = !netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_WALK_DONT_CHECK_LEXICOGRAPHIC); if (netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_WALK_INCLUDE_REQUESTED)) { snmp_get_and_print(ss, root, rootlen); } while (running) { /* * create PDU for GETBULK request and add object name to request */ pdu = snmp_pdu_create(SNMP_MSG_GETBULK); pdu->non_repeaters = non_reps; pdu->max_repetitions = reps; /* fill the packet */ snmp_add_null_var(pdu, name, name_length); /* * do the request */ status = snmp_synch_response(ss, pdu, &response); if (status == STAT_SUCCESS) { if (response->errstat == SNMP_ERR_NOERROR) { /* * check resulting variables */ for (vars = response->variables; vars; vars = vars->next_variable) { if ((vars->name_length < rootlen) || (memcmp(root, vars->name, rootlen * sizeof(oid)) != 0)) { /* * not part of this subtree */ running = 0; continue; } numprinted++; print_variable(vars->name, vars->name_length, vars); if ((vars->type != SNMP_ENDOFMIBVIEW) && (vars->type != SNMP_NOSUCHOBJECT) && (vars->type != SNMP_NOSUCHINSTANCE)) { /* * not an exception value */ if (check && snmp_oid_compare(name, name_length, vars->name, vars->name_length) >= 0) { fprintf(stderr, "Error: OID not increasing: "); fprint_objid(stderr, name, name_length); fprintf(stderr, " >= "); fprint_objid(stderr, vars->name, vars->name_length); fprintf(stderr, "\n"); running = 0; exitval = 1; } /* * Check if last variable, and if so, save for next request. */ if (vars->next_variable == NULL) { memmove(name, vars->name, vars->name_length * sizeof(oid)); name_length = vars->name_length; } } else { /* * an exception value, so stop */ running = 0; } } } else { /* * error in response, print it */ running = 0; if (response->errstat == SNMP_ERR_NOSUCHNAME) { printf("End of MIB\n"); } else { fprintf(stderr, "Error in packet.\nReason: %s\n", snmp_errstring(response->errstat)); if (response->errindex != 0) { fprintf(stderr, "Failed object: "); for (count = 1, vars = response->variables; vars && count != response->errindex; vars = vars->next_variable, count++) /*EMPTY*/; if (vars) fprint_objid(stderr, vars->name, vars->name_length); fprintf(stderr, "\n"); } exitval = 2; } } } else if (status == STAT_TIMEOUT) { fprintf(stderr, "Timeout: No Response from %s\n", session.peername); running = 0; exitval = 1; } else { /* status == STAT_ERROR */ snmp_sess_perror("snmpbulkwalk", ss); running = 0; exitval = 1; } if (response) snmp_free_pdu(response); } if (numprinted == 0 && status == STAT_SUCCESS) { /* * no printed successful results, which may mean we were * pointed at an only existing instance. Attempt a GET, just * for get measure. */ snmp_get_and_print(ss, root, rootlen); } snmp_close(ss); if (netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_WALK_PRINT_STATISTICS)) { printf("Variables found: %d\n", numprinted); } SOCK_CLEANUP; return exitval; }
int main(int argc, char *argv[]) { netsnmp_session session, *ss; netsnmp_pdu *pdu = NULL, *response = NULL; #ifdef notused netsnmp_variable_list *vars; #endif int arg; #ifdef notused int count; int current_name = 0; int current_type = 0; int current_value = 0; char *names[128]; char types[128]; char *values[128]; oid name[MAX_OID_LEN]; #endif size_t name_length = USM_OID_LEN; size_t name_length2 = USM_OID_LEN; int status; int exitval = 0; int rval; int command = 0; long longvar; size_t oldKu_len = SNMP_MAXBUF_SMALL, newKu_len = SNMP_MAXBUF_SMALL, oldkul_len = SNMP_MAXBUF_SMALL, newkul_len = SNMP_MAXBUF_SMALL, keychange_len = SNMP_MAXBUF_SMALL; char *newpass = NULL, *oldpass = NULL; u_char oldKu[SNMP_MAXBUF_SMALL], newKu[SNMP_MAXBUF_SMALL], oldkul[SNMP_MAXBUF_SMALL], newkul[SNMP_MAXBUF_SMALL], keychange[SNMP_MAXBUF_SMALL]; authKeyChange = authKeyOid; privKeyChange = privKeyOid; /* * get the common command line arguments */ switch (arg = snmp_parse_args(argc, argv, &session, "C:", optProc)) { case -2: exit(0); case -1: usage(); exit(1); default: break; } SOCK_STARTUP; /* * open an SNMP session */ /* * Note: this wil obtain the engineID needed below */ ss = snmp_open(&session); if (ss == NULL) { /* * diagnose snmp_open errors with the input netsnmp_session pointer */ snmp_sess_perror("snmpusm", &session); exit(1); } /* * create PDU for SET request and add object names and values to request */ pdu = snmp_pdu_create(SNMP_MSG_SET); if (arg >= argc) { fprintf(stderr, "Please specify a operation to perform.\n"); usage(); exit(1); } if (strcmp(argv[arg], CMD_PASSWD_NAME) == 0) { /* * passwd: change a users password. * * XXX: Uses the auth type of the calling user, a MD5 user can't * change a SHA user's key. */ command = CMD_PASSWD; oldpass = argv[++arg]; newpass = argv[++arg]; if (doprivkey == 0 && doauthkey == 0) doprivkey = doauthkey = 1; if (newpass == NULL || strlen(newpass) < USM_LENGTH_P_MIN) { fprintf(stderr, "New passphrase must be greater than %d characters in length.\n", USM_LENGTH_P_MIN); exit(1); } if (oldpass == NULL || strlen(oldpass) < USM_LENGTH_P_MIN) { fprintf(stderr, "Old passphrase must be greater than %d characters in length.\n", USM_LENGTH_P_MIN); exit(1); } /* * do we have a securityName? If not, copy the default */ if (session.securityName == NULL) { session.securityName = strdup(netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SECNAME)); } /* * the old Ku is in the session, but we need the new one */ if (session.securityAuthProto == NULL) { /* * get .conf set default */ const oid *def = get_default_authtype(&session.securityAuthProtoLen); session.securityAuthProto = snmp_duplicate_objid(def, session.securityAuthProtoLen); } if (session.securityAuthProto == NULL) { /* * assume MD5 */ session.securityAuthProtoLen = sizeof(usmHMACMD5AuthProtocol) / sizeof(oid); session.securityAuthProto = snmp_duplicate_objid(usmHMACMD5AuthProtocol, session.securityAuthProtoLen); } rval = generate_Ku(session.securityAuthProto, session.securityAuthProtoLen, (u_char *) newpass, strlen(newpass), newKu, &newKu_len); if (rval != SNMPERR_SUCCESS) { snmp_perror(argv[0]); fprintf(stderr, "generating the old Ku failed\n"); exit(1); } /* * the old Ku is in the session, but we need the new one */ rval = generate_Ku(session.securityAuthProto, session.securityAuthProtoLen, (u_char *) oldpass, strlen(oldpass), oldKu, &oldKu_len); if (rval != SNMPERR_SUCCESS) { snmp_perror(argv[0]); fprintf(stderr, "generating the new Ku failed\n"); exit(1); } /* * generate the two Kul's */ rval = generate_kul(session.securityAuthProto, session.securityAuthProtoLen, ss->contextEngineID, ss->contextEngineIDLen, oldKu, oldKu_len, oldkul, &oldkul_len); if (rval != SNMPERR_SUCCESS) { snmp_perror(argv[0]); fprintf(stderr, "generating the old Kul failed\n"); exit(1); } rval = generate_kul(session.securityAuthProto, session.securityAuthProtoLen, ss->contextEngineID, ss->contextEngineIDLen, newKu, newKu_len, newkul, &newkul_len); if (rval != SNMPERR_SUCCESS) { snmp_perror(argv[0]); fprintf(stderr, "generating the new Kul failed\n"); exit(1); } /* * create the keychange string */ rval = encode_keychange(session.securityAuthProto, session.securityAuthProtoLen, oldkul, oldkul_len, newkul, newkul_len, keychange, &keychange_len); if (rval != SNMPERR_SUCCESS) { snmp_perror(argv[0]); fprintf(stderr, "encoding the keychange failed\n"); usage(); exit(1); } /* * add the keychange string to the outgoing packet */ if (doauthkey) { setup_oid(authKeyChange, &name_length, ss->contextEngineID, ss->contextEngineIDLen, session.securityName); snmp_pdu_add_variable(pdu, authKeyChange, name_length, ASN_OCTET_STR, keychange, keychange_len); } if (doprivkey) { setup_oid(privKeyChange, &name_length, ss->contextEngineID, ss->contextEngineIDLen, session.securityName); snmp_pdu_add_variable(pdu, privKeyChange, name_length, ASN_OCTET_STR, keychange, keychange_len); } } else if (strcmp(argv[arg], CMD_CREATE_NAME) == 0) { /* * create: create a user * * create USER [CLONEFROM] */ if (++arg >= argc) { fprintf(stderr, "You must specify the user name to create\n"); usage(); exit(1); } command = CMD_CREATE; if (++arg < argc) { /* * clone the new user from an existing user * (and make them active immediately) */ setup_oid(usmUserStatus, &name_length, ss->contextEngineID, ss->contextEngineIDLen, argv[arg-1]); longvar = RS_CREATEANDGO; snmp_pdu_add_variable(pdu, usmUserStatus, name_length, ASN_INTEGER, (u_char *) & longvar, sizeof(longvar)); setup_oid(usmUserCloneFrom, &name_length, ss->contextEngineID, ss->contextEngineIDLen, argv[arg - 1]); setup_oid(usmUserSecurityName, &name_length2, ss->contextEngineID, ss->contextEngineIDLen, argv[arg]); snmp_pdu_add_variable(pdu, usmUserCloneFrom, name_length, ASN_OBJECT_ID, (u_char *) usmUserSecurityName, sizeof(oid) * name_length2); } else { /* * create a new (unauthenticated) user from scratch * The Net-SNMP agent won't allow such a user to be made active. */ setup_oid(usmUserStatus, &name_length, ss->contextEngineID, ss->contextEngineIDLen, argv[arg-1]); longvar = RS_CREATEANDWAIT; snmp_pdu_add_variable(pdu, usmUserStatus, name_length, ASN_INTEGER, (u_char *) & longvar, sizeof(longvar)); } } else if (strcmp(argv[arg], CMD_CLONEFROM_NAME) == 0) { /* * create: clone a user from another * * cloneFrom USER FROM */ if (++arg >= argc) { fprintf(stderr, "You must specify the user name to operate on\n"); usage(); exit(1); } command = CMD_CLONEFROM; setup_oid(usmUserStatus, &name_length, ss->contextEngineID, ss->contextEngineIDLen, argv[arg]); longvar = RS_ACTIVE; snmp_pdu_add_variable(pdu, usmUserStatus, name_length, ASN_INTEGER, (u_char *) & longvar, sizeof(longvar)); setup_oid(usmUserCloneFrom, &name_length, ss->contextEngineID, ss->contextEngineIDLen, argv[arg]); if (++arg >= argc) { fprintf(stderr, "You must specify the user name to clone from\n"); usage(); exit(1); } setup_oid(usmUserSecurityName, &name_length2, ss->contextEngineID, ss->contextEngineIDLen, argv[arg]); snmp_pdu_add_variable(pdu, usmUserCloneFrom, name_length, ASN_OBJECT_ID, (u_char *) usmUserSecurityName, sizeof(oid) * name_length2); } else if (strcmp(argv[arg], CMD_DELETE_NAME) == 0) { /* * delete: delete a user * * delete USER */ if (++arg >= argc) { fprintf(stderr, "You must specify the user name to delete\n"); exit(1); } command = CMD_DELETE; setup_oid(usmUserStatus, &name_length, ss->contextEngineID, ss->contextEngineIDLen, argv[arg]); longvar = RS_DESTROY; snmp_pdu_add_variable(pdu, usmUserStatus, name_length, ASN_INTEGER, (u_char *) & longvar, sizeof(longvar)); } else { fprintf(stderr, "Unknown command\n"); usage(); exit(1); } /* * do the request */ status = snmp_synch_response(ss, pdu, &response); if (status == STAT_SUCCESS) { if (response) { if (response->errstat == SNMP_ERR_NOERROR) { fprintf(stderr, "%s\n", successNotes[command - 1]); } else { fprintf(stderr, "Error in packet.\nReason: %s\n", snmp_errstring(response->errstat)); if (response->errindex != 0) { int count; netsnmp_variable_list *vars; fprintf(stderr, "Failed object: "); for (count = 1, vars = response->variables; vars && count != response->errindex; vars = vars->next_variable, count++) /*EMPTY*/; if (vars) fprint_objid(stderr, vars->name, vars->name_length); fprintf(stderr, "\n"); } exitval = 2; } } } else if (status == STAT_TIMEOUT) { fprintf(stderr, "Timeout: No Response from %s\n", session.peername); exitval = 1; } else { /* status == STAT_ERROR */ snmp_sess_perror("snmpset", ss); exitval = 1; } if (response) snmp_free_pdu(response); snmp_close(ss); SOCK_CLEANUP; return exitval; }
int snmpps(int argc, char *argv[]) { netsnmp_session session, *ss; int arg; struct hrSWRunTable *procs; int count, pinx = 0; /* * get the common command line arguments */ switch (arg = snmp_parse_args(argc, argv, &session, "C:", optProc)) { case NETSNMP_PARSE_ARGS_ERROR: exit(1); case NETSNMP_PARSE_ARGS_SUCCESS_EXIT: exit(0); case NETSNMP_PARSE_ARGS_ERROR_USAGE: usage(); exit(1); default: break; } if (arg != argc) { fprintf(stderr, "snmpps: extra argument: %s\n", argv[arg]); exit(1); } SOCK_STARTUP; /* * Open an SNMP session. */ ss = snmp_open(&session); if (ss == NULL) { /* * diagnose snmp_open errors with the input netsnmp_session pointer */ snmp_sess_perror("snmpps", &session); SOCK_CLEANUP; exit(1); } count = collect_perf(ss, &procs); if (count == 0) { fprintf(stderr, "snmpps: no processes found\n"); exit(1); } switch (topsort) { case 'm': qsort(procs, count, sizeof(procs[0]), memcomp); break; case 't': qsort(procs, count, sizeof(procs[0]), totcomp); break; } printf("%7s %4s %6s %10s %11s %-10s\n", "Index", "Type", "Status", "Memory", "CPU", "Command"); while (pinx < count) { struct hrSWRunTable *proc = procs+pinx; const char *hr_status, *hr_type; char b1[15], b2[20]; switch (proc->hrSWRunType) { case 1: hr_type = "Unkn"; break; case 2: hr_type = "Os"; break; case 3: hr_type = "Drvr"; break; case 4: hr_type = "Appl"; break; default: hr_type = "?"; break; } switch (proc->hrSWRunStatus) { case 1: hr_status = "Run"; break; case 2: hr_status = "Wait"; break; case 3: hr_status = "Event"; break; case 4: hr_status = "Inval"; break; default: hr_status = "?"; break; } printf("%7lu %4s %6s %10s %11.11s %s %s\n", proc->hrSWRunIndex, hr_type, hr_status, format_humanmem(b1, sizeof b1, proc->hrSWRunPerfMem), format_centisec(b2, sizeof b2, proc->hrSWRunPerfCPU), command_path && proc->hrSWRunPath[0] ? proc->hrSWRunPath : proc->hrSWRunName, command_args ? proc->hrSWRunParameters : ""); pinx++; } snmp_close(ss); SOCK_CLEANUP; return 0; }
void proxy_parse_config(const char *token, char *line) { /* * proxy args [base-oid] [remap-to-remote-oid] */ netsnmp_session session, *ss; struct simple_proxy *newp, **listpp; char args[MAX_ARGS][SPRINT_MAX_LEN], *argv[MAX_ARGS]; int argn, arg; char *cp; netsnmp_handler_registration *reg; context_string = NULL; DEBUGMSGTL(("proxy_config", "entering\n")); /* * create the argv[] like array */ strcpy(argv[0] = args[0], "snmpd-proxy"); /* bogus entry for getopt() */ for (argn = 1, cp = line; cp && argn < MAX_ARGS;) { argv[argn] = args[argn]; cp = copy_nword(cp, argv[argn], SPRINT_MAX_LEN); argn++; } for (arg = 0; arg < argn; arg++) { DEBUGMSGTL(("proxy_args", "final args: %d = %s\n", arg, argv[arg])); } DEBUGMSGTL(("proxy_config", "parsing args: %d\n", argn)); /* Call special parse_args that allows for no specified community string */ arg = snmp_parse_args(argn, argv, &session, "C:", proxyOptProc); /* reset this in case we modified it */ netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_IGNORE_NO_COMMUNITY, 0); if (arg < 0) { config_perror("failed to parse proxy args"); return; } DEBUGMSGTL(("proxy_config", "done parsing args\n")); if (arg >= argn) { config_perror("missing base oid"); return; } /* * usm_set_reportErrorOnUnknownID(0); * * hack, stupid v3 ASIs. */ /* * XXX: on a side note, we don't really need to be a reference * platform any more so the proper thing to do would be to fix * snmplib/snmpusm.c to pass in the pdu type to usm_process_incoming * so this isn't needed. */ ss = snmp_open(&session); /* * usm_set_reportErrorOnUnknownID(1); */ if (ss == NULL) { /* * diagnose snmp_open errors with the input netsnmp_session pointer */ snmp_sess_perror("snmpget", &session); SOCK_CLEANUP; return; } newp = (struct simple_proxy *) calloc(1, sizeof(struct simple_proxy)); newp->sess = ss; DEBUGMSGTL(("proxy_init", "name = %s\n", args[arg])); newp->name_len = MAX_OID_LEN; if (!snmp_parse_oid(args[arg++], newp->name, &newp->name_len)) { snmp_perror("proxy"); config_perror("illegal proxy oid specified\n"); return; } if (arg < argn) { DEBUGMSGTL(("proxy_init", "base = %s\n", args[arg])); newp->base_len = MAX_OID_LEN; if (!snmp_parse_oid(args[arg++], newp->base, &newp->base_len)) { snmp_perror("proxy"); config_perror("illegal variable name specified (base oid)\n"); return; } } if ( context_string ) newp->context = strdup(context_string); DEBUGMSGTL(("proxy_init", "registering at: ")); DEBUGMSGOID(("proxy_init", newp->name, newp->name_len)); DEBUGMSG(("proxy_init", "\n")); /* * add to our chain */ /* * must be sorted! */ listpp = &proxies; while (*listpp && snmp_oid_compare(newp->name, newp->name_len, (*listpp)->name, (*listpp)->name_len) > 0) { listpp = &((*listpp)->next); } /* * listpp should be next in line from us. */ if (*listpp) { /* * make our next in the link point to the current link */ newp->next = *listpp; } /* * replace current link with us */ *listpp = newp; reg = netsnmp_create_handler_registration("proxy", proxy_handler, newp->name, newp->name_len, HANDLER_CAN_RWRITE); reg->handler->myvoid = newp; if (context_string) reg->contextName = strdup(context_string); netsnmp_register_handler(reg); }
int main(int argc, char *argv[]) { netsnmp_session session, *ss; netsnmp_pdu *pdu = NULL, *response = NULL; int arg; size_t name_length = USM_OID_LEN; size_t name_length2 = USM_OID_LEN; int status; int exitval = 1; int rval; int command = 0; long longvar; size_t oldKu_len = SNMP_MAXBUF_SMALL, newKu_len = SNMP_MAXBUF_SMALL, oldkul_len = SNMP_MAXBUF_SMALL, oldkulpriv_len = SNMP_MAXBUF_SMALL, newkulpriv_len = SNMP_MAXBUF_SMALL, newkul_len = SNMP_MAXBUF_SMALL, keychange_len = SNMP_MAXBUF_SMALL, keychangepriv_len = SNMP_MAXBUF_SMALL; char *newpass = NULL, *oldpass = NULL; u_char oldKu[SNMP_MAXBUF_SMALL], newKu[SNMP_MAXBUF_SMALL], oldkul[SNMP_MAXBUF_SMALL], oldkulpriv[SNMP_MAXBUF_SMALL], newkulpriv[SNMP_MAXBUF_SMALL], newkul[SNMP_MAXBUF_SMALL], keychange[SNMP_MAXBUF_SMALL], keychangepriv[SNMP_MAXBUF_SMALL]; SOCK_STARTUP; authKeyChange = authKeyOid; privKeyChange = privKeyOid; /* * get the common command line arguments */ switch (arg = snmp_parse_args(argc, argv, &session, "C:", optProc)) { case NETSNMP_PARSE_ARGS_ERROR: goto out; case NETSNMP_PARSE_ARGS_SUCCESS_EXIT: exitval = 0; goto out; case NETSNMP_PARSE_ARGS_ERROR_USAGE: usage(); goto out; default: break; } if (arg >= argc) { fprintf(stderr, "Please specify an operation to perform.\n"); usage(); goto out; } /* * open an SNMP session */ /* * Note: this needs to obtain the engineID used below */ session.flags &= ~SNMP_FLAGS_DONT_PROBE; ss = snmp_open(&session); if (ss == NULL) { /* * diagnose snmp_open errors with the input netsnmp_session pointer */ snmp_sess_perror("snmpusm", &session); goto out; } /* * set usmUserEngineID from ss->contextEngineID * if not already set (via -CE) */ if (usmUserEngineID == NULL) { usmUserEngineID = ss->contextEngineID; usmUserEngineIDLen = ss->contextEngineIDLen; } /* * create PDU for SET request and add object names and values to request */ pdu = snmp_pdu_create(SNMP_MSG_SET); if (!pdu) { fprintf(stderr, "Failed to create request\n"); goto close_session; } if (strcmp(argv[arg], CMD_PASSWD_NAME) == 0) { /* * passwd: change a users password. * * XXX: Uses the auth type of the calling user, a MD5 user can't * change a SHA user's key. */ char *passwd_user; command = CMD_PASSWD; oldpass = argv[++arg]; newpass = argv[++arg]; passwd_user = argv[++arg]; if (doprivkey == 0 && doauthkey == 0) doprivkey = doauthkey = 1; if (newpass == NULL || strlen(newpass) < USM_LENGTH_P_MIN) { fprintf(stderr, "New passphrase must be greater than %d characters in length.\n", USM_LENGTH_P_MIN); goto close_session; } if (oldpass == NULL || strlen(oldpass) < USM_LENGTH_P_MIN) { fprintf(stderr, "Old passphrase must be greater than %d characters in length.\n", USM_LENGTH_P_MIN); goto close_session; } DEBUGMSGTL(("9:usm:passwd", "oldpass len %" NETSNMP_PRIz "d, newpass len %" NETSNMP_PRIz "d\n", strlen(oldpass), strlen(newpass))); /* * Change the user supplied on command line. */ if ((passwd_user != NULL) && (strlen(passwd_user) > 0)) { session.securityName = passwd_user; } else { /* * Use own key object if no user was supplied. */ authKeyChange = ownAuthKeyOid; privKeyChange = ownPrivKeyOid; } /* * do we have a securityName? If not, copy the default */ if (session.securityName == NULL) { session.securityName = strdup(netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SECNAME)); } /* * the old Ku is in the session, but we need the new one */ if (session.securityAuthProto == NULL) { /* * get .conf set default */ const oid *def = get_default_authtype(&session.securityAuthProtoLen); session.securityAuthProto = snmp_duplicate_objid(def, session.securityAuthProtoLen); } if (session.securityAuthProto == NULL) { /* * assume MD5 */ #ifndef NETSNMP_DISABLE_MD5 session.securityAuthProtoLen = sizeof(usmHMACMD5AuthProtocol) / sizeof(oid); session.securityAuthProto = snmp_duplicate_objid(usmHMACMD5AuthProtocol, session.securityAuthProtoLen); #else session.securityAuthProtoLen = sizeof(usmHMACSHA1AuthProtocol) / sizeof(oid); session.securityAuthProto = snmp_duplicate_objid(usmHMACSHA1AuthProtocol, session.securityAuthProtoLen); #endif } if (uselocalizedkey && (strncmp(oldpass, "0x", 2) == 0)) { /* * use the localized key from the command line */ u_char *buf; size_t buf_len = SNMP_MAXBUF_SMALL; buf = (u_char *) malloc (buf_len * sizeof(u_char)); oldkul_len = 0; /* initialize the offset */ if (!snmp_hex_to_binary((u_char **) (&buf), &buf_len, &oldkul_len, 0, oldpass)) { snmp_perror(argv[0]); fprintf(stderr, "generating the old Kul from localized key failed\n"); goto close_session; } memcpy(oldkul, buf, oldkul_len); SNMP_FREE(buf); } else { /* * the old Ku is in the session, but we need the new one */ rval = generate_Ku(session.securityAuthProto, session.securityAuthProtoLen, (u_char *) oldpass, strlen(oldpass), oldKu, &oldKu_len); if (rval != SNMPERR_SUCCESS) { snmp_perror(argv[0]); fprintf(stderr, "generating the old Ku failed\n"); goto close_session; } /* * generate the two Kul's */ rval = generate_kul(session.securityAuthProto, session.securityAuthProtoLen, usmUserEngineID, usmUserEngineIDLen, oldKu, oldKu_len, oldkul, &oldkul_len); if (rval != SNMPERR_SUCCESS) { snmp_perror(argv[0]); fprintf(stderr, "generating the old Kul failed\n"); goto close_session; } DEBUGMSGTL(("9:usm:passwd", "oldkul len %" NETSNMP_PRIz "d\n", oldkul_len)); } if (uselocalizedkey && (strncmp(newpass, "0x", 2) == 0)) { /* * use the localized key from the command line */ u_char *buf; size_t buf_len = SNMP_MAXBUF_SMALL; buf = (u_char *) malloc (buf_len * sizeof(u_char)); newkul_len = 0; /* initialize the offset */ if (!snmp_hex_to_binary((u_char **) (&buf), &buf_len, &newkul_len, 0, newpass)) { snmp_perror(argv[0]); fprintf(stderr, "generating the new Kul from localized key failed\n"); goto close_session; } memcpy(newkul, buf, newkul_len); SNMP_FREE(buf); } else { rval = generate_Ku(session.securityAuthProto, session.securityAuthProtoLen, (u_char *) newpass, strlen(newpass), newKu, &newKu_len); if (rval != SNMPERR_SUCCESS) { snmp_perror(argv[0]); fprintf(stderr, "generating the new Ku failed\n"); goto close_session; } rval = generate_kul(session.securityAuthProto, session.securityAuthProtoLen, usmUserEngineID, usmUserEngineIDLen, newKu, newKu_len, newkul, &newkul_len); if (rval != SNMPERR_SUCCESS) { snmp_perror(argv[0]); fprintf(stderr, "generating the new Kul failed\n"); goto close_session; } DEBUGMSGTL(("9:usm:passwd", "newkul len %" NETSNMP_PRIz "d\n", newkul_len)); } /* * for encryption, we may need to truncate the key to the proper length * so we need two copies. For simplicity, we always just copy even if * they're the same lengths. */ if (doprivkey) { int privtype, properlength; u_char *okp = oldkulpriv, *nkp = newkulpriv; if (!session.securityPrivProto) { snmp_log(LOG_ERR, "no encryption type specified, which I need in order to know to change the key\n"); goto close_session; } privtype = sc_get_privtype(session.securityPrivProto, session.securityPrivProtoLen); properlength = sc_get_proper_priv_length_bytype(privtype); if (USM_CREATE_USER_PRIV_DES == privtype) properlength *= 2; /* ?? we store salt with key */ DEBUGMSGTL(("9:usm:passwd", "proper len %d\n", properlength)); oldkulpriv_len = oldkul_len; newkulpriv_len = newkul_len; memcpy(oldkulpriv, oldkul, oldkulpriv_len); memcpy(newkulpriv, newkul, newkulpriv_len); if (oldkulpriv_len > properlength) { oldkulpriv_len = newkulpriv_len = properlength; } else if (oldkulpriv_len < properlength) { rval = netsnmp_extend_kul(properlength, session.securityAuthProto, session.securityAuthProtoLen, privtype, usmUserEngineID, usmUserEngineIDLen, &okp, &oldkulpriv_len, sizeof(oldkulpriv)); rval = netsnmp_extend_kul(properlength, session.securityAuthProto, session.securityAuthProtoLen, privtype, usmUserEngineID, usmUserEngineIDLen, &nkp, &newkulpriv_len, sizeof(newkulpriv)); } } /* * create the keychange string */ if (doauthkey) { rval = encode_keychange(session.securityAuthProto, session.securityAuthProtoLen, oldkul, oldkul_len, newkul, newkul_len, keychange, &keychange_len); if (rval != SNMPERR_SUCCESS) { snmp_perror(argv[0]); fprintf(stderr, "encoding the keychange failed\n"); usage(); goto close_session; } } /* which is slightly different for encryption if lengths are different */ if (doprivkey) { DEBUGMSGTL(("9:usm:passwd:encode", "proper len %" NETSNMP_PRIz "d, old_len %" NETSNMP_PRIz "d, new_len %" NETSNMP_PRIz "d\n", oldkulpriv_len, oldkulpriv_len, newkulpriv_len)); rval = encode_keychange(session.securityAuthProto, session.securityAuthProtoLen, oldkulpriv, oldkulpriv_len, newkulpriv, newkulpriv_len, keychangepriv, &keychangepriv_len); DEBUGMSGTL(("9:usm:passwd:encode", "keychange len %" NETSNMP_PRIz "d\n", keychangepriv_len)); if (rval != SNMPERR_SUCCESS) { snmp_perror(argv[0]); fprintf(stderr, "encoding the keychange failed\n"); usage(); goto close_session; } } /* * add the keychange string to the outgoing packet */ if (doauthkey) { setup_oid(authKeyChange, &name_length, usmUserEngineID, usmUserEngineIDLen, session.securityName); snmp_pdu_add_variable(pdu, authKeyChange, name_length, ASN_OCTET_STR, keychange, keychange_len); } if (doprivkey) { setup_oid(privKeyChange, &name_length2, usmUserEngineID, usmUserEngineIDLen, session.securityName); snmp_pdu_add_variable(pdu, privKeyChange, name_length2, ASN_OCTET_STR, keychangepriv, keychangepriv_len); } } else if (strcmp(argv[arg], CMD_CREATE_NAME) == 0) { /* * create: create a user * * create USER [CLONEFROM] */ if (++arg >= argc) { fprintf(stderr, "You must specify the user name to create\n"); usage(); goto close_session; } command = CMD_CREATE; if (++arg < argc) { /* * clone the new user from an existing user * (and make them active immediately) */ setup_oid(usmUserStatus, &name_length, usmUserEngineID, usmUserEngineIDLen, argv[arg-1]); if (docreateandwait) { longvar = RS_CREATEANDWAIT; } else { longvar = RS_CREATEANDGO; } snmp_pdu_add_variable(pdu, usmUserStatus, name_length, ASN_INTEGER, (u_char *) & longvar, sizeof(longvar)); name_length = USM_OID_LEN; setup_oid(usmUserCloneFrom, &name_length, usmUserEngineID, usmUserEngineIDLen, argv[arg - 1]); setup_oid(usmUserSecurityName, &name_length2, usmUserEngineID, usmUserEngineIDLen, argv[arg]); snmp_pdu_add_variable(pdu, usmUserCloneFrom, name_length, ASN_OBJECT_ID, (u_char *) usmUserSecurityName, sizeof(oid) * name_length2); } else { /* * create a new (unauthenticated) user from scratch * The Net-SNMP agent won't allow such a user to be made active. */ setup_oid(usmUserStatus, &name_length, usmUserEngineID, usmUserEngineIDLen, argv[arg-1]); longvar = RS_CREATEANDWAIT; snmp_pdu_add_variable(pdu, usmUserStatus, name_length, ASN_INTEGER, (u_char *) & longvar, sizeof(longvar)); } } else if (strcmp(argv[arg], CMD_CLONEFROM_NAME) == 0) { /* * create: clone a user from another * * cloneFrom USER FROM */ if (++arg >= argc) { fprintf(stderr, "You must specify the user name to operate on\n"); usage(); goto close_session; } command = CMD_CLONEFROM; setup_oid(usmUserStatus, &name_length, usmUserEngineID, usmUserEngineIDLen, argv[arg]); longvar = RS_ACTIVE; snmp_pdu_add_variable(pdu, usmUserStatus, name_length, ASN_INTEGER, (u_char *) & longvar, sizeof(longvar)); name_length = USM_OID_LEN; setup_oid(usmUserCloneFrom, &name_length, usmUserEngineID, usmUserEngineIDLen, argv[arg]); if (++arg >= argc) { fprintf(stderr, "You must specify the user name to clone from\n"); usage(); goto close_session; } setup_oid(usmUserSecurityName, &name_length2, usmUserEngineID, usmUserEngineIDLen, argv[arg]); snmp_pdu_add_variable(pdu, usmUserCloneFrom, name_length, ASN_OBJECT_ID, (u_char *) usmUserSecurityName, sizeof(oid) * name_length2); } else if (strcmp(argv[arg], CMD_DELETE_NAME) == 0) { /* * delete: delete a user * * delete USER */ if (++arg >= argc) { fprintf(stderr, "You must specify the user name to delete\n"); goto close_session; } command = CMD_DELETE; setup_oid(usmUserStatus, &name_length, usmUserEngineID, usmUserEngineIDLen, argv[arg]); longvar = RS_DESTROY; snmp_pdu_add_variable(pdu, usmUserStatus, name_length, ASN_INTEGER, (u_char *) & longvar, sizeof(longvar)); } else if (strcmp(argv[arg], CMD_ACTIVATE_NAME) == 0) { /* * activate: activate a user * * activate USER */ if (++arg >= argc) { fprintf(stderr, "You must specify the user name to activate\n"); goto close_session; } command = CMD_ACTIVATE; setup_oid(usmUserStatus, &name_length, usmUserEngineID, usmUserEngineIDLen, argv[arg]); longvar = RS_ACTIVE; snmp_pdu_add_variable(pdu, usmUserStatus, name_length, ASN_INTEGER, (u_char *) & longvar, sizeof(longvar)); } else if (strcmp(argv[arg], CMD_DEACTIVATE_NAME) == 0) { /* * deactivate: deactivate a user * * deactivate USER */ if (++arg >= argc) { fprintf(stderr, "You must specify the user name to deactivate\n"); goto close_session; } command = CMD_DEACTIVATE; setup_oid(usmUserStatus, &name_length, usmUserEngineID, usmUserEngineIDLen, argv[arg]); longvar = RS_NOTINSERVICE; snmp_pdu_add_variable(pdu, usmUserStatus, name_length, ASN_INTEGER, (u_char *) & longvar, sizeof(longvar)); #if defined(HAVE_OPENSSL_DH_H) && defined(HAVE_LIBCRYPTO) } else if (strcmp(argv[arg], CMD_CHANGEKEY_NAME) == 0) { /* * change the key of a user if DH is available */ char *passwd_user; netsnmp_pdu *dhpdu, *dhresponse = NULL; netsnmp_variable_list *vars, *dhvar; command = CMD_CHANGEKEY; name_length = DH_USM_OID_LEN; name_length2 = DH_USM_OID_LEN; passwd_user = argv[++arg]; if (doprivkey == 0 && doauthkey == 0) doprivkey = doauthkey = 1; /* * Change the user supplied on command line. */ if ((passwd_user != NULL) && (strlen(passwd_user) > 0)) { session.securityName = passwd_user; } else { /* * Use own key object if no user was supplied. */ dhauthKeyChange = usmDHUserOwnAuthKeyChange; dhprivKeyChange = usmDHUserOwnPrivKeyChange; } /* * do we have a securityName? If not, copy the default */ if (session.securityName == NULL) { session.securityName = strdup(netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SECNAME)); } /* fetch the needed diffie helman parameters */ dhpdu = snmp_pdu_create(SNMP_MSG_GET); if (!dhpdu) { fprintf(stderr, "Failed to create DH request\n"); goto close_session; } /* get the current DH parameters */ snmp_add_null_var(dhpdu, usmDHParameters, usmDHParameters_len); /* maybe the auth key public value */ if (doauthkey) { setup_oid(dhauthKeyChange, &name_length, usmUserEngineID, usmUserEngineIDLen, session.securityName); snmp_add_null_var(dhpdu, dhauthKeyChange, name_length); } /* maybe the priv key public value */ if (doprivkey) { setup_oid(dhprivKeyChange, &name_length2, usmUserEngineID, usmUserEngineIDLen, session.securityName); snmp_add_null_var(dhpdu, dhprivKeyChange, name_length2); } /* fetch the values */ status = snmp_synch_response(ss, dhpdu, &dhresponse); if (status != SNMPERR_SUCCESS || dhresponse == NULL || dhresponse->errstat != SNMP_ERR_NOERROR || dhresponse->variables->type != ASN_OCTET_STR) { snmp_sess_perror("snmpusm", ss); if (dhresponse && dhresponse->variables && dhresponse->variables->type != ASN_OCTET_STR) { fprintf(stderr, "Can't get diffie-helman exchange from the agent\n"); fprintf(stderr, " (maybe it doesn't support the SNMP-USM-DH-OBJECTS-MIB MIB)\n"); } exitval = 1; goto begone; } dhvar = dhresponse->variables; vars = dhvar->next_variable; /* complete the DH equation & print resulting keys */ if (doauthkey) { if (get_USM_DH_key(vars, dhvar, sc_get_properlength(ss->securityAuthProto, ss->securityAuthProtoLen), pdu, "auth", dhauthKeyChange, name_length) != SNMPERR_SUCCESS) goto begone; vars = vars->next_variable; } if (doprivkey) { size_t dhprivKeyLen = 0; int privtype = sc_get_privtype(ss->securityPrivProto, ss->securityPrivProtoLen); dhprivKeyLen = sc_get_proper_priv_length_bytype(privtype); if (USM_CREATE_USER_PRIV_DES == privtype) dhprivKeyLen *= 2; /* ?? we store salt with key */ if (get_USM_DH_key(vars, dhvar, dhprivKeyLen, pdu, "priv", dhprivKeyChange, name_length2) != SNMPERR_SUCCESS) goto begone; vars = vars->next_variable; } /* snmp_free_pdu(dhresponse); */ /* parts still in use somewhere */ #endif /* HAVE_OPENSSL_DH_H && HAVE_LIBCRYPTO */ } else { fprintf(stderr, "Unknown command\n"); usage(); goto close_session; } /* * add usmUserPublic if specified (via -Cp) */ if (usmUserPublic_val) { name_length = USM_OID_LEN; setup_oid(usmUserPublic, &name_length, usmUserEngineID, usmUserEngineIDLen, session.securityName); snmp_pdu_add_variable(pdu, usmUserPublic, name_length, ASN_OCTET_STR, usmUserPublic_val, strlen(usmUserPublic_val)); } /* * do the request */ status = snmp_synch_response(ss, pdu, &response); if (status == STAT_SUCCESS) { if (response) { if (response->errstat == SNMP_ERR_NOERROR) { fprintf(stdout, "%s\n", successNotes[command - 1]); } else { fprintf(stderr, "Error in packet.\nReason: %s\n", snmp_errstring(response->errstat)); if (response->errindex != 0) { int count; netsnmp_variable_list *vars; fprintf(stderr, "Failed object: "); for (count = 1, vars = response->variables; vars && count != response->errindex; vars = vars->next_variable, count++) /*EMPTY*/; if (vars) fprint_objid(stderr, vars->name, vars->name_length); fprintf(stderr, "\n"); } exitval = 2; } } } else if (status == STAT_TIMEOUT) { fprintf(stderr, "Timeout: No Response from %s\n", session.peername); exitval = 1; } else { /* status == STAT_ERROR */ snmp_sess_perror("snmpset", ss); exitval = 1; } exitval = 0; #if defined(HAVE_OPENSSL_DH_H) && defined(HAVE_LIBCRYPTO) begone: #endif /* HAVE_OPENSSL_DH_H && HAVE_LIBCRYPTO */ if (response) snmp_free_pdu(response); close_session: snmp_close(ss); out: SOCK_CLEANUP; return exitval; }
int main(int argc, char *argv[]) { struct snmp_session session, *ss; struct snmp_pdu *pdu; struct snmp_pdu *response; struct variable_list *vars; int arg; int count; int current_name = 0; char *names[128]; oid name[MAX_OID_LEN]; int name_length; int status; /* get the common command line arguments */ arg = snmp_parse_args(argc, argv, &session); /* get the object names */ for(; arg < argc; arg++) names[current_name++] = argv[arg]; SOCK_STARTUP; /* open an SNMP session */ snmp_synch_setup(&session); ss = snmp_open(&session); if (ss == NULL){ snmp_perror("snmpget"); SOCK_CLEANUP; exit(1); } /* create PDU for GET request and add object names to request */ pdu = snmp_pdu_create(SNMP_MSG_GET); for(count = 0; count < current_name; count++){ name_length = MAX_OID_LEN; if (!snmp_parse_oid(names[count], name, &name_length)) { fprintf(stderr, "Invalid object identifier: %s\n", names[count]); failures++; } else snmp_add_null_var(pdu, name, name_length); } if (failures) { SOCK_CLEANUP; exit(1); } /* do the request */ retry: status = snmp_synch_response(ss, pdu, &response); if (status == STAT_SUCCESS){ if (response->errstat == SNMP_ERR_NOERROR){ for(vars = response->variables; vars; vars = vars->next_variable) print_variable(vars->name, vars->name_length, vars); } else { fprintf(stderr, "Error in packet\nReason: %s\n", snmp_errstring(response->errstat)); if (response->errstat == SNMP_ERR_NOSUCHNAME){ fprintf(stderr, "This name doesn't exist: "); for(count = 1, vars = response->variables; vars && count != response->errindex; vars = vars->next_variable, count++) ; if (vars) fprint_objid(stderr, vars->name, vars->name_length); fprintf(stderr, "\n"); } if ((pdu = snmp_fix_pdu(response, SNMP_MSG_GET)) != NULL) goto retry; } } else if (status == STAT_TIMEOUT){ fprintf(stderr,"Timeout: No Response from %s.\n", session.peername); snmp_close(ss); SOCK_CLEANUP; exit(1); } else { /* status == STAT_ERROR */ snmp_perror("snmpget"); snmp_close(ss); SOCK_CLEANUP; exit(1); } if (response) snmp_free_pdu(response); snmp_close(ss); SOCK_CLEANUP; exit (0); }
int main(int argc, char **argv) { netsnmp_session session, *ss; netsnmp_variable_list *var_list = NULL; int arg, rc, rs_idx; u_int hash_type; char *fingerprint, *tmp; /* * get the common command line arguments */ switch (arg = snmp_parse_args(argc, argv, &session, "C:", optProc)) { case NETSNMP_PARSE_ARGS_ERROR: exit(1); case NETSNMP_PARSE_ARGS_SUCCESS_EXIT: exit(0); case NETSNMP_PARSE_ARGS_ERROR_USAGE: usage(); default: break; } /* * Open an SNMP session. */ SOCK_STARTUP; ss = snmp_open(&session); if (ss == NULL) { /* * diagnose snmp_open errors with the input netsnmp_session pointer */ snmp_sess_perror("snmptls", &session); SOCK_CLEANUP; exit(1); } if (strcmp(argv[arg], "certToSecName") == 0) { oid map_type[MAX_OID_LEN]; u_int pri; size_t map_type_len; if (strcmp(argv[++arg], "add") != 0) { fprintf(stderr, "only add is supported at this time\n"); exit(1); } pri = atoi(argv[++arg]); tmp = argv[++arg]; hash_type = atoi(tmp); fingerprint = argv[++arg]; DEBUGMSGT(("snmptls", "create pri %d, hash type %d, fp %s", pri, hash_type, fingerprint)); if (_map_type_str) { map_type_len = MAX_OID_LEN; if (snmp_parse_oid(_map_type_str, map_type, &map_type_len) == NULL) { snmp_perror(_map_type_str); exit(1); } DEBUGMSG(("snmptls", ", map type ")); DEBUGMSGOID(("snmptls", map_type, map_type_len)); } if (_data) DEBUGMSG(("snmptls", ", data %s", _data)); _parse_storage_type(_storage_type_str); DEBUGMSG(("snmptls", "\n")); var_list = cert_row_create(pri, hash_type, fingerprint, map_type, map_type_len, (u_char*)_data, _data_len, _storage_type, &rs_idx); } else if (strcmp(argv[arg], "targetParamsFingerprint") == 0) { char * params_name; if (strcmp(argv[++arg], "add") != 0) { fprintf(stderr, "only add is supported at this time\n"); exit(1); } params_name = argv[++arg]; hash_type = atoi(argv[++arg]); fingerprint = argv[++arg]; _parse_storage_type(_storage_type_str); DEBUGMSGT(("snmptls", "create %s param fp, hash type %d, fp %s\n", params_name, hash_type, fingerprint)); var_list = params_row_create(params_name, hash_type, fingerprint, _storage_type, &rs_idx); } else if (strcmp(argv[arg], "targetAddr") == 0) { char * addr_name; if (strcmp(argv[++arg], "add") != 0) { fprintf(stderr, "only add is supported at this time\n"); exit(1); } addr_name = argv[++arg]; _parse_storage_type(_storage_type_str); DEBUGMSGT(("snmptls", "create %s addr fp, hash type %d, fp %s, id %s\n", addr_name, _hash_type, _fp_str, _id_str)); var_list = addr_row_create(addr_name, _hash_type, _fp_str, _id_str, _storage_type, &rs_idx); } if (! var_list) { fprintf(stderr, "no command specified\n"); usage(); } rc = netsnmp_row_create(ss, var_list, rs_idx); SOCK_CLEANUP; return 0; }
int main(int argc, char *argv[]) { netsnmp_session session, *ss; netsnmp_pdu *pdu, *response; netsnmp_variable_list *vars; int arg; char *gateway; int count; struct varInfo *vip; u_int value = 0; struct counter64 c64value; float printvalue; time_t last_time = 0; time_t this_time; time_t delta_time; int sum; /* what the heck is this for, its never used? */ char filename[128] = { 0 }; struct timeval tv; struct tm tm; char timestring[64] = { 0 }, valueStr[64] = { 0}, maxStr[64] = { 0}; char outstr[256] = { 0 }, peakStr[64] = { 0}; int status; int begin, end, last_end; int print = 1; int exit_code = 1; SOCK_STARTUP; switch (arg = snmp_parse_args(argc, argv, &session, "C:", &optProc)) { case NETSNMP_PARSE_ARGS_ERROR: goto out; case NETSNMP_PARSE_ARGS_SUCCESS_EXIT: exit_code = 0; goto out; case NETSNMP_PARSE_ARGS_ERROR_USAGE: usage(); goto out; default: break; } gateway = session.peername; for (; optind < argc; optind++) { if (current_name >= MAX_ARGS) { fprintf(stderr, "%s: Too many variables specified (max %d)\n", argv[optind], MAX_ARGS); goto out; } varinfo[current_name++].name = argv[optind]; } if (current_name == 0) { usage(); goto out; } if (dosum) { if (current_name >= MAX_ARGS) { fprintf(stderr, "Too many variables specified (max %d)\n", MAX_ARGS); goto out; } varinfo[current_name++].name = NULL; } /* * open an SNMP session */ ss = snmp_open(&session); if (ss == NULL) { /* * diagnose snmp_open errors with the input netsnmp_session pointer */ snmp_sess_perror("snmpdelta", &session); goto out; } if (tableForm && timestamp) { printf("%s", gateway); } for (count = 0; count < current_name; count++) { vip = varinfo + count; if (vip->name) { vip->oidlen = MAX_OID_LEN; vip->info_oid = (oid *) malloc(sizeof(oid) * vip->oidlen); if (snmp_parse_oid(vip->name, vip->info_oid, &vip->oidlen) == NULL) { snmp_perror(vip->name); goto close_session; } sprint_descriptor(vip->descriptor, vip); if (tableForm) printf("\t%s", vip->descriptor); } else { vip->oidlen = 0; strlcpy(vip->descriptor, SumFile, sizeof(vip->descriptor)); } vip->value = 0; zeroU64(&vip->c64value); vip->time = 0; vip->max = 0; if (peaks) { vip->peak_count = -1; vip->peak = 0; vip->peak_average = 0; } } wait_for_period(period); end = current_name; sum = 0; while (1) { pdu = snmp_pdu_create(SNMP_MSG_GET); if (deltat) snmp_add_null_var(pdu, sysUpTimeOid, sysUpTimeLen); if (end == current_name) count = 0; else count = end; begin = count; for (; count < current_name && count < begin + varbindsPerPacket - deltat; count++) { if (varinfo[count].oidlen) snmp_add_null_var(pdu, varinfo[count].info_oid, varinfo[count].oidlen); } last_end = end; end = count; retry: status = snmp_synch_response(ss, pdu, &response); if (status == STAT_SUCCESS) { if (response->errstat == SNMP_ERR_NOERROR) { if (timestamp) { gettimeofday(&tv, (struct timezone *) 0); memcpy(&tm, localtime((time_t *) & tv.tv_sec), sizeof(tm)); if (((period % 60) && (!peaks || ((period * peaks) % 60))) || keepSeconds) sprintf(timestring, " [%02d:%02d:%02d %d/%d]", tm.tm_hour, tm.tm_min, tm.tm_sec, tm.tm_mon + 1, tm.tm_mday); else sprintf(timestring, " [%02d:%02d %d/%d]", tm.tm_hour, tm.tm_min, tm.tm_mon + 1, tm.tm_mday); } vars = response->variables; if (deltat) { if (!vars || !vars->val.integer) { fprintf(stderr, "Missing variable in reply\n"); continue; } else { this_time = *(vars->val.integer); } vars = vars->next_variable; } else { this_time = 1; } for (count = begin; count < end; count++) { vip = varinfo + count; if (vip->oidlen) { if (!vars || !vars->val.integer) { fprintf(stderr, "Missing variable in reply\n"); break; } vip->type = vars->type; if (vars->type == ASN_COUNTER64) { u64Subtract(vars->val.counter64, &vip->c64value, &c64value); memcpy(&vip->c64value, vars->val.counter64, sizeof(struct counter64)); } else { value = *(vars->val.integer) - vip->value; vip->value = *(vars->val.integer); } vars = vars->next_variable; } else { value = sum; sum = 0; } delta_time = this_time - vip->time; if (delta_time <= 0) delta_time = 100; last_time = vip->time; vip->time = this_time; if (last_time == 0) continue; if (vip->oidlen && vip->type != ASN_COUNTER64) { sum += value; } if (tableForm) { if (count == begin) { sprintf(outstr, "%s", timestring + 1); } else { outstr[0] = '\0'; } } else { sprintf(outstr, "%s %s", timestring, vip->descriptor); } if (deltat || tableForm) { if (vip->type == ASN_COUNTER64) { fprintf(stderr, "time delta and table form not supported for counter64s\n"); goto close_session; } else { printvalue = ((float) value * 100) / delta_time; if (tableForm) sprintf(valueStr, "\t%.2f", printvalue); else sprintf(valueStr, " /sec: %.2f", printvalue); } } else { printvalue = (float) value; sprintf(valueStr, " /%d sec: ", period); if (vip->type == ASN_COUNTER64) printU64(valueStr + strlen(valueStr), &c64value); else sprintf(valueStr + strlen(valueStr), "%u", value); } if (!peaks) { strcat(outstr, valueStr); } else { print = 0; if (vip->peak_count == -1) { if (wait_for_peak_start(period, peaks) == 0) vip->peak_count = 0; } else { vip->peak_average += printvalue; if (vip->peak < printvalue) vip->peak = printvalue; if (++vip->peak_count == peaks) { if (deltat) sprintf(peakStr, " /sec: %.2f (%d sec Peak: %.2f)", vip->peak_average / vip->peak_count, period, vip->peak); else sprintf(peakStr, " /%d sec: %.0f (%d sec Peak: %.0f)", period, vip->peak_average / vip->peak_count, period, vip->peak); vip->peak_average = 0; vip->peak = 0; vip->peak_count = 0; print = 1; strcat(outstr, peakStr); } } } if (printmax) { if (printvalue > vip->max) { vip->max = printvalue; } if (deltat) sprintf(maxStr, " (Max: %.2f)", vip->max); else sprintf(maxStr, " (Max: %.0f)", vip->max); strcat(outstr, maxStr); } if (print) { if (fileout) { sprintf(filename, "%s-%s", gateway, vip->descriptor); print_log(filename, outstr + 1); } else { if (tableForm) printf("%s", outstr); else printf("%s\n", outstr + 1); fflush(stdout); } } } if (end == last_end && tableForm) printf("\n"); } else { if (response->errstat == SNMP_ERR_TOOBIG) { if (response->errindex <= varbindsPerPacket && response->errindex > 0) { varbindsPerPacket = response->errindex - 1; } else { if (varbindsPerPacket > 30) varbindsPerPacket -= 5; else varbindsPerPacket--; } if (varbindsPerPacket <= 0) { exit_code = 5; break; } end = last_end; continue; } else if (response->errindex != 0) { fprintf(stderr, "Failed object: "); for (count = 1, vars = response->variables; vars && count != response->errindex; vars = vars->next_variable, count++); if (vars) fprint_objid(stderr, vars->name, vars->name_length); fprintf(stderr, "\n"); /* * Don't exit when OIDs from file are not found on agent * exit_code = 1; * break; */ } else { fprintf(stderr, "Error in packet: %s\n", snmp_errstring(response->errstat)); exit_code = 1; break; } /* * retry if the errored variable was successfully removed */ if (!netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_APP_DONT_FIX_PDUS)) { pdu = snmp_fix_pdu(response, SNMP_MSG_GET); snmp_free_pdu(response); response = NULL; if (pdu != NULL) goto retry; } } } else if (status == STAT_TIMEOUT) { fprintf(stderr, "Timeout: No Response from %s\n", gateway); response = NULL; exit_code = 1; break; } else { /* status == STAT_ERROR */ snmp_sess_perror("snmpdelta", ss); response = NULL; exit_code = 1; break; } if (response) snmp_free_pdu(response); if (end == current_name) { wait_for_period(period); } } exit_code = 0; close_session: snmp_close(ss); out: SOCK_CLEANUP; return (exit_code); }
int main (int argc, char *argv[]) { netsnmp_session session, *ss; netsnmp_pdu *pdu = NULL, *response = NULL; #ifdef notused netsnmp_variable_list *vars; #endif int arg; #ifdef notused int count; int current_name = 0; int current_type = 0; int current_value = 0; char *names[128]; char types[128]; char *values[128]; oid name[MAX_OID_LEN]; #endif size_t name_length; int status; int exitval = 0; int command = 0; long longvar; int secModel, secLevel, contextMatch; unsigned int val, i = 0; char *mask, *groupName, *prefix, *authtype; u_char viewMask[VACMSTRINGLEN]; char *st; /* * get the common command line arguments */ switch (arg = snmp_parse_args (argc, argv, &session, "C:", optProc)) { case NETSNMP_PARSE_ARGS_ERROR: exit (1); case NETSNMP_PARSE_ARGS_SUCCESS_EXIT: exit (0); case NETSNMP_PARSE_ARGS_ERROR_USAGE: usage (); exit (1); default: break; } SOCK_STARTUP; /* * open an SNMP session */ /* * Note: this wil obtain the engineID needed below */ ss = snmp_open (&session); if (ss == NULL) { /* * diagnose snmp_open errors with the input netsnmp_session pointer */ snmp_sess_perror ("snmpvacm", &session); exit (1); } /* * create PDU for SET request and add object names and values to request */ pdu = snmp_pdu_create (SNMP_MSG_SET); if (arg >= argc) { fprintf (stderr, "Please specify a operation to perform.\n"); usage (); exit (1); } if (strcmp (argv[arg], CMD_DELETEVIEW_NAME) == 0) /* * deleteView: delete a view * * deleteView NAME SUBTREE * */ { if (++arg + 2 != argc) { fprintf (stderr, "You must specify the view to delete\n"); usage (); exit (1); } command = CMD_DELETEVIEW; name_length = VIEW_OID_LEN; view_oid (vacmViewTreeFamilyStatus, &name_length, argv[arg], argv[arg + 1]); longvar = RS_DESTROY; snmp_pdu_add_variable (pdu, vacmViewTreeFamilyStatus, name_length, ASN_INTEGER, (u_char *) & longvar, sizeof (longvar)); } else if (strcmp (argv[arg], CMD_CREATEVIEW_NAME) == 0) /* * createView: create a view * * createView NAME SUBTREE MASK * */ { if (++arg + 2 > argc) { fprintf (stderr, "You must specify name, subtree and mask\n"); usage (); exit (1); } command = CMD_CREATEVIEW; name_length = VIEW_OID_LEN; view_oid (vacmViewTreeFamilyStatus, &name_length, argv[arg], argv[arg + 1]); longvar = RS_CREATEANDGO; snmp_pdu_add_variable (pdu, vacmViewTreeFamilyStatus, name_length, ASN_INTEGER, (u_char *) & longvar, sizeof (longvar)); /* * Mask */ if (arg + 3 == argc) { mask = argv[arg + 2]; for (mask = strtok_r (mask, ".:", &st); mask; mask = strtok_r (NULL, ".:", &st)) { if (i >= sizeof (viewMask)) { printf ("MASK too long\n"); exit (1); } if (sscanf (mask, "%x", &val) == 0) { printf ("invalid MASK\n"); exit (1); } viewMask[i] = val; i++; } } else { for (i = 0; i < (name_length + 7) / 8; i++) viewMask[i] = (u_char) 0xff; } view_oid (vacmViewTreeFamilyMask, &name_length, argv[arg], argv[arg + 1]); snmp_pdu_add_variable (pdu, vacmViewTreeFamilyMask, name_length, ASN_OCTET_STR, viewMask, i); view_oid (vacmViewTreeFamilyType, &name_length, argv[arg], argv[arg + 1]); snmp_pdu_add_variable (pdu, vacmViewTreeFamilyType, name_length, ASN_INTEGER, (u_char *) & viewTreeFamilyType, sizeof (viewTreeFamilyType)); } else if (strcmp (argv[arg], CMD_DELETESEC2GROUP_NAME) == 0) /* * deleteSec2Group: delete security2group * * deleteSec2Group MODEL SECURITYNAME * */ { if (++arg + 2 != argc) { fprintf (stderr, "You must specify the sec2group to delete\n"); usage (); exit (1); } command = CMD_DELETESEC2GROUP; name_length = SEC2GROUP_OID_LEN; if (sscanf (argv[arg], "%d", &secModel) == 0) { printf ("invalid security model\n"); usage (); exit (1); } sec2group_oid (vacmSec2GroupStatus, &name_length, secModel, argv[arg + 1]); longvar = RS_DESTROY; snmp_pdu_add_variable (pdu, vacmSec2GroupStatus, name_length, ASN_INTEGER, (u_char *) & longvar, sizeof (longvar)); } else if (strcmp (argv[arg], CMD_CREATESEC2GROUP_NAME) == 0) /* * createSec2Group: create a security2group * * createSec2Group MODEL SECURITYNAME GROUPNAME * */ { if (++arg + 3 != argc) { fprintf (stderr, "You must specify model, security name and group name\n"); usage (); exit (1); } command = CMD_CREATESEC2GROUP; name_length = SEC2GROUP_OID_LEN; if (sscanf (argv[arg], "%d", &secModel) == 0) { printf ("invalid security model\n"); usage (); exit (1); } sec2group_oid (vacmSec2GroupStatus, &name_length, secModel, argv[arg + 1]); longvar = RS_CREATEANDGO; snmp_pdu_add_variable (pdu, vacmSec2GroupStatus, name_length, ASN_INTEGER, (u_char *) & longvar, sizeof (longvar)); sec2group_oid (vacmGroupName, &name_length, secModel, argv[arg + 1]); snmp_pdu_add_variable (pdu, vacmGroupName, name_length, ASN_OCTET_STR, (u_char *) argv[arg + 2], strlen (argv[arg + 2])); } else if (strcmp (argv[arg], CMD_DELETEACCESS_NAME) == 0) /* * deleteAccess: delete access entry * * deleteAccess GROUPNAME [CONTEXTPREFIX] SECURITYMODEL SECURITYLEVEL * */ { if (++arg + 3 > argc) { fprintf (stderr, "You must specify the access entry to delete\n"); usage (); exit (1); } command = CMD_DELETEACCESS; name_length = ACCESS_OID_LEN; groupName = argv[arg]; if (arg + 4 == argc) prefix = argv[++arg]; else prefix = NULL; if (sscanf (argv[arg + 1], "%d", &secModel) == 0) { printf ("invalid security model\n"); usage (); exit (1); } if (sscanf (argv[arg + 2], "%d", &secLevel) == 0) { printf ("invalid security level\n"); usage (); exit (1); } access_oid (vacmAccessStatus, &name_length, groupName, prefix, secModel, secLevel); longvar = RS_DESTROY; snmp_pdu_add_variable (pdu, vacmAccessStatus, name_length, ASN_INTEGER, (u_char *) & longvar, sizeof (longvar)); } else if (strcmp (argv[arg], CMD_CREATEACCESS_NAME) == 0) /* * createAccess: create access entry * * createAccess GROUPNAME [CONTEXTPREFIX] SECURITYMODEL SECURITYLEVEL CONTEXTMATCH READVIEWNAME WRITEVIEWNAME NOTIFYVIEWNAME * */ { if (++arg + 7 > argc) { fprintf (stderr, "You must specify the access entry to create\n"); usage (); exit (1); } command = CMD_CREATEACCESS; name_length = ACCESS_OID_LEN; groupName = argv[arg]; if (arg + 8 == argc) prefix = argv[++arg]; else prefix = NULL; if (sscanf (argv[arg + 1], "%d", &secModel) == 0) { printf ("invalid security model\n"); usage (); exit (1); } if (sscanf (argv[arg + 2], "%d", &secLevel) == 0) { printf ("invalid security level\n"); usage (); exit (1); } access_oid (vacmAccessStatus, &name_length, groupName, prefix, secModel, secLevel); longvar = RS_CREATEANDGO; snmp_pdu_add_variable (pdu, vacmAccessStatus, name_length, ASN_INTEGER, (u_char *) & longvar, sizeof (longvar)); access_oid (vacmAccessContextMatch, &name_length, groupName, prefix, secModel, secLevel); if (sscanf (argv[arg + 3], "%d", &contextMatch) == 0) { printf ("invalid contextMatch\n"); usage (); exit (1); } snmp_pdu_add_variable (pdu, vacmAccessContextMatch, name_length, ASN_INTEGER, (u_char *) & contextMatch, sizeof (contextMatch)); access_oid (vacmAccessReadViewName, &name_length, groupName, prefix, secModel, secLevel); snmp_pdu_add_variable (pdu, vacmAccessReadViewName, name_length, ASN_OCTET_STR, (u_char *) argv[arg + 4], strlen (argv[arg + 4])); access_oid (vacmAccessWriteViewName, &name_length, groupName, prefix, secModel, secLevel); snmp_pdu_add_variable (pdu, vacmAccessWriteViewName, name_length, ASN_OCTET_STR, (u_char *) argv[arg + 5], strlen (argv[arg + 5])); access_oid (vacmAccessNotifyViewName, &name_length, groupName, prefix, secModel, secLevel); snmp_pdu_add_variable (pdu, vacmAccessNotifyViewName, name_length, ASN_OCTET_STR, (u_char *) argv[arg + 6], strlen (argv[arg + 6])); } else if (strcmp (argv[arg], CMD_DELETEAUTH_NAME) == 0) /* * deleteAuth: delete authAccess entry * * deleteAuth GROUPNAME [CONTEXTPREFIX] SECURITYMODEL SECURITYLEVEL AUTHTYPE * */ { if (++arg + 4 > argc) { fprintf (stderr, "You must specify the authAccess entry to delete\n"); usage (); exit (1); } command = CMD_DELETEAUTH; name_length = AUTH_OID_LEN; groupName = argv[arg]; if (arg + 5 == argc) prefix = argv[++arg]; else prefix = NULL; if (sscanf (argv[arg + 1], "%d", &secModel) == 0) { printf ("invalid security model\n"); usage (); exit (1); } if (sscanf (argv[arg + 2], "%d", &secLevel) == 0) { printf ("invalid security level\n"); usage (); exit (1); } authtype = argv[arg + 3]; auth_oid (nsVacmRowStatus, &name_length, groupName, prefix, secModel, secLevel, authtype); longvar = RS_DESTROY; snmp_pdu_add_variable (pdu, nsVacmRowStatus, name_length, ASN_INTEGER, (u_char *) & longvar, sizeof (longvar)); } else if (strcmp (argv[arg], CMD_CREATEAUTH_NAME) == 0) /* * createAuth: create authAccess entry * * createAuth GROUPNAME [CONTEXTPREFIX] SECURITYMODEL SECURITYLEVEL AUTHTYPE CONTEXTMATCH VIEWNAME * */ { if (++arg + 6 > argc) { fprintf (stderr, "You must specify the authAccess entry to create\n"); usage (); exit (1); } command = CMD_CREATEAUTH; name_length = AUTH_OID_LEN; groupName = argv[arg]; if (arg + 7 == argc) prefix = argv[++arg]; else prefix = NULL; if (sscanf (argv[arg + 1], "%d", &secModel) == 0) { printf ("invalid security model\n"); usage (); exit (1); } if (sscanf (argv[arg + 2], "%d", &secLevel) == 0) { printf ("invalid security level\n"); usage (); exit (1); } authtype = argv[arg + 3]; auth_oid (nsVacmRowStatus, &name_length, groupName, prefix, secModel, secLevel, authtype); longvar = RS_CREATEANDGO; snmp_pdu_add_variable (pdu, nsVacmRowStatus, name_length, ASN_INTEGER, (u_char *) & longvar, sizeof (longvar)); auth_oid (nsVacmContextPfx, &name_length, groupName, prefix, secModel, secLevel, authtype); if (sscanf (argv[arg + 4], "%d", &contextMatch) == 0) { printf ("invalid contextMatch\n"); usage (); exit (1); } snmp_pdu_add_variable (pdu, nsVacmContextPfx, name_length, ASN_INTEGER, (u_char *) & contextMatch, sizeof (contextMatch)); auth_oid (nsVacmViewName, &name_length, groupName, prefix, secModel, secLevel, authtype); snmp_pdu_add_variable (pdu, nsVacmViewName, name_length, ASN_OCTET_STR, (u_char *) argv[arg + 5], strlen (argv[arg + 5])); } else { printf ("Unknown command\n"); usage (); exit (1); } /* * do the request */ status = snmp_synch_response (ss, pdu, &response); if (status == STAT_SUCCESS) { if (response) { if (response->errstat == SNMP_ERR_NOERROR) { fprintf (stderr, "%s\n", successNotes[command - 1]); } else { fprintf (stderr, "Error in packet.\nReason: %s\n", snmp_errstring (response->errstat)); if (response->errindex != 0) { int count; struct variable_list *vars = response->variables; fprintf (stderr, "Failed object: "); for (count = 1; vars && (count != response->errindex); vars = vars->next_variable, count++) ; if (vars) fprint_objid (stderr, vars->name, vars->name_length); fprintf (stderr, "\n"); } exitval = 2; } } } else if (status == STAT_TIMEOUT) { fprintf (stderr, "Timeout: No Response from %s\n", session.peername); exitval = 1; } else { snmp_sess_perror ("snmpset", ss); exitval = 1; } if (response) snmp_free_pdu (response); snmp_close (ss); SOCK_CLEANUP; return exitval; }
int main(int argc, char *argv[]) { netsnmp_session session, *ss; int total_entries = 0; netsnmp_set_line_buffering(stdout); netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, 1); /* * get the common command line arguments */ switch (snmp_parse_args(argc, argv, &session, "C:", optProc)) { case NETSNMP_PARSE_ARGS_ERROR: exit(1); case NETSNMP_PARSE_ARGS_SUCCESS_EXIT: exit(0); case NETSNMP_PARSE_ARGS_ERROR_USAGE: usage(); exit(1); default: break; } /* * get the initial object and subtree */ /* * specified on the command line */ if (optind + 1 != argc) { fprintf(stderr, "Must have exactly one table name\n"); usage(); exit(1); } rootlen = MAX_OID_LEN; if (!snmp_parse_oid(argv[optind], root, &rootlen)) { snmp_perror(argv[optind]); exit(1); } localdebug = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DUMP_PACKET); get_field_names(); reverse_fields(); /* * open an SNMP session */ SOCK_STARTUP; ss = snmp_open(&session); if (ss == NULL) { /* * diagnose snmp_open errors with the input netsnmp_session pointer */ snmp_sess_perror("snmptable", &session); SOCK_CLEANUP; exit(1); } #ifndef NETSNMP_DISABLE_SNMPV1 if (ss->version == SNMP_VERSION_1) use_getbulk = 0; #endif do { entries = 0; allocated = 0; if (!headers_only) { if (use_getbulk) getbulk_table_entries(ss); else get_table_entries(ss); } if (exitval) { snmp_close(ss); SOCK_CLEANUP; return exitval; } if (entries || headers_only) print_table(); if (data) { free (data); data = NULL; } if (indices) { free (indices); indices = NULL; } total_entries += entries; } while (!end_of_table); snmp_close(ss); SOCK_CLEANUP; if (total_entries == 0) printf("%s: No entries\n", table_name); if (extra_columns) printf("%s: WARNING: More columns on agent than in MIB\n", table_name); return 0; }
int main (int argc, char *argv[]) { netsnmp_session session, *ss; netsnmp_pdu *pdu; netsnmp_pdu *response; netsnmp_variable_list *vars; int arg; int count; int status; int exitval = 0; /* * get the common command line arguments */ switch (arg = snmp_parse_args (argc, argv, &session, "C:", optProc)) { case NETSNMP_PARSE_ARGS_ERROR: exit (1); case NETSNMP_PARSE_ARGS_SUCCESS_EXIT: exit (0); case NETSNMP_PARSE_ARGS_ERROR_USAGE: usage (); exit (1); default: break; } names = argc - arg; if (names < non_repeaters) { fprintf (stderr, "snmpbulkget: need more objects than <nonrep>\n"); exit (1); } namep = name = (struct nameStruct *) calloc (names, sizeof (*name)); while (arg < argc) { namep->name_len = MAX_OID_LEN; if (snmp_parse_oid (argv[arg], namep->name, &namep->name_len) == NULL) { snmp_perror (argv[arg]); exit (1); } arg++; namep++; } SOCK_STARTUP; /* * open an SNMP session */ ss = snmp_open (&session); if (ss == NULL) { /* * diagnose snmp_open errors with the input netsnmp_session pointer */ snmp_sess_perror ("snmpbulkget", &session); SOCK_CLEANUP; exit (1); } /* * create PDU for GETBULK request and add object name to request */ pdu = snmp_pdu_create (SNMP_MSG_GETBULK); pdu->non_repeaters = non_repeaters; pdu->max_repetitions = max_repetitions; /* fill the packet */ for (arg = 0; arg < names; arg++) snmp_add_null_var (pdu, name[arg].name, name[arg].name_len); /* * do the request */ status = snmp_synch_response (ss, pdu, &response); if (status == STAT_SUCCESS) { if (response->errstat == SNMP_ERR_NOERROR) { /* * check resulting variables */ for (vars = response->variables; vars; vars = vars->next_variable) print_variable (vars->name, vars->name_length, vars); } else { /* * error in response, print it */ if (response->errstat == SNMP_ERR_NOSUCHNAME) { printf ("End of MIB.\n"); } else { fprintf (stderr, "Error in packet.\nReason: %s\n", snmp_errstring (response->errstat)); if (response->errindex != 0) { fprintf (stderr, "Failed object: "); for (count = 1, vars = response->variables; vars && (count != response->errindex); vars = vars->next_variable, count++) /*EMPTY*/; if (vars) fprint_objid (stderr, vars->name, vars->name_length); fprintf (stderr, "\n"); } exitval = 2; } } } else if (status == STAT_TIMEOUT) { fprintf (stderr, "Timeout: No Response from %s\n", session.peername); exitval = 1; } else { /* status == STAT_ERROR */ snmp_sess_perror ("snmpbulkget", ss); exitval = 1; } if (response) snmp_free_pdu (response); snmp_close (ss); SOCK_CLEANUP; return exitval; }
void snmpd_parse_config_trapsess(const char *word, char *cptr) { char *argv[MAX_ARGS], *cp = cptr, tmp[SPRINT_MAX_LEN]; int argn, arg; netsnmp_session session, *ss; size_t len; /* * inform or trap? default to trap */ traptype = SNMP_MSG_TRAP2; /* * create the argv[] like array */ argv[0] = strdup("snmpd-trapsess"); /* bogus entry for getopt() */ for (argn = 1; cp && argn < MAX_ARGS; argn++) { cp = copy_nword(cp, tmp, SPRINT_MAX_LEN); argv[argn] = strdup(tmp); } arg = snmp_parse_args(argn, argv, &session, "C:", trapOptProc); ss = snmp_add(&session, netsnmp_transport_open_client("snmptrap", session.peername), NULL, NULL); for (; argn > 0; argn--) { free(argv[argn - 1]); } if (!ss) { config_perror ("snmpd: failed to parse this line or the remote trap receiver is down. Possible cause:"); snmp_sess_perror("snmpd: snmpd_parse_config_trapsess()", &session); return; } /* * If this is an SNMPv3 TRAP session, then the agent is * the authoritative engine, so set the engineID accordingly */ if (ss->version == SNMP_VERSION_3 && traptype != SNMP_MSG_INFORM && ss->securityEngineIDLen == 0) { len = snmpv3_get_engineID( tmp, sizeof(tmp)); memdup(&ss->securityEngineID, tmp, len); ss->securityEngineIDLen = len; } #ifndef NETSNMP_DISABLE_SNMPV1 if (ss->version == SNMP_VERSION_1) { add_trap_session(ss, SNMP_MSG_TRAP, 0, SNMP_VERSION_1); } else { #endif add_trap_session(ss, traptype, (traptype == SNMP_MSG_INFORM), ss->version); #ifndef NETSNMP_DISABLE_SNMPV1 } #endif }
int snmptop(int argc, char **argv) { netsnmp_session session, *ss; int arg; struct hrSWRunTable *oproc; int ocount = 0; int show_idle = 1; int show_os = 1; char ch; struct cpuStats oldCpu; struct memStats mem; int has_cpu, has_mem; /* * get the common command line arguments */ switch (arg = snmp_parse_args(argc, argv, &session, "C:", optProc)) { case NETSNMP_PARSE_ARGS_ERROR: exit(1); case NETSNMP_PARSE_ARGS_SUCCESS_EXIT: exit(0); case NETSNMP_PARSE_ARGS_ERROR_USAGE: usage(); exit(1); default: break; } if (arg != argc) { fprintf(stderr, "snmptop: extra argument: %s\n", argv[arg]); exit(1); } SOCK_STARTUP; /* * Open an SNMP session. */ ss = snmp_open(&session); if (ss == NULL) { /* * diagnose snmp_open errors with the input netsnmp_session pointer */ snmp_sess_perror("snmptop", &session); SOCK_CLEANUP; exit(1); } ocount = collect_perf(ss, &oproc); if (ocount == 0) { fprintf(stderr, "snmptop: no processes found\n"); exit(1); } collect_cpu(ss, &oldCpu); signal(SIGINT, endtop); initscr(); cbreak(); noecho(); nonl(); halfdelay(50); while ((ch = getch()) != 'q') { int ncount; struct hrSWRunTable *nproc; int oinx = 0, ninx = 0, line = 0; netsnmp_pdu *pdu; netsnmp_pdu *response = NULL; int status; time_t clock; struct tm *ptm; char uptime[40]; char timestr[40]; char b1[15], b2[15], b3[15], b4[15]; struct cpuStats newCpu; if (ch == 'c' || ch == 'm' || ch == 'n' || ch == 't') topsort = ch; if (ch == 'i') show_idle = !show_idle; if (ch == 'o') show_os = !show_os; if (ch == 'a') command_args = !command_args; if (ch == 'p') command_path = !command_path; ncount = collect_perf(ss, &nproc); while (oinx < ocount && ninx < ncount) { if (oproc[oinx].hrSWRunIndex == nproc[ninx].hrSWRunIndex) { nproc[ninx].hrSWRunPerfCPUInc = nproc[ninx].hrSWRunPerfCPU-oproc[oinx].hrSWRunPerfCPU; ninx++; oinx++; } else if (nproc[oinx].hrSWRunIndex < oproc[ninx].hrSWRunIndex) oinx++; else { nproc[ninx].hrSWRunPerfCPUInc = nproc[ninx].hrSWRunPerfCPU; ninx++; } } while (ninx < ncount) { nproc[ninx].hrSWRunPerfCPUInc = nproc[ninx].hrSWRunPerfCPU; ninx++; } switch (topsort) { case 'c': qsort(nproc, ncount, sizeof(nproc[0]), cpucomp); break; case 'm': qsort(nproc, ncount, sizeof(nproc[0]), memcomp); break; case 't': qsort(nproc, ncount, sizeof(nproc[0]), totcomp); break; } has_cpu = collect_cpu(ss, &newCpu); has_mem = collect_mem(ss, &mem); pdu = snmp_pdu_create(SNMP_MSG_GET); add(pdu, "HOST-RESOURCES-MIB:hrSystemUptime.0", NULL, 0); status = snmp_synch_response(ss, pdu, &response); if (status != STAT_SUCCESS || !response || response->errstat != SNMP_ERR_NOERROR) { uptime[0] = '\0'; } else { netsnmp_variable_list *vlp = response->variables; if (vlp->type == SNMP_NOSUCHINSTANCE) abort(); uptime_string_n(*vlp->val.integer, uptime, sizeof(uptime)); } snmp_free_pdu(response); clock = time(NULL); ptm = localtime(&clock); strftime(timestr, sizeof(timestr), "%H:%M:%S", ptm); clear(); move(0, 0); printw("%s %s%s", session.peername, uptime[0] ? "up " : "", uptime); move(0, COLS-strlen(timestr)-1); printw("%s", timestr); if (has_cpu) { struct cpuStats deltaCpu; u_long sumCpu; deltaCpu.user = newCpu.user - oldCpu.user; deltaCpu.nice = newCpu.nice - oldCpu.nice; deltaCpu.system = newCpu.system - oldCpu.system; deltaCpu.idle = newCpu.idle - oldCpu.idle; deltaCpu.wait = newCpu.wait - oldCpu.wait; deltaCpu.kernel = newCpu.kernel - oldCpu.kernel; deltaCpu.intr = newCpu.intr - oldCpu.intr; deltaCpu.softintr = newCpu.softintr - oldCpu.softintr; deltaCpu.steal = newCpu.steal - oldCpu.steal; deltaCpu.guest = newCpu.guest - oldCpu.guest; deltaCpu.guestnice = newCpu.guestnice - oldCpu.guestnice; oldCpu = newCpu; sumCpu = deltaCpu.user + deltaCpu.nice + deltaCpu.system + deltaCpu.idle + deltaCpu.wait + deltaCpu.kernel + deltaCpu.steal + deltaCpu.intr + deltaCpu.softintr + deltaCpu.guest + deltaCpu.guestnice; printw("\nCPU%%: %4.1fUs %4.1fSy %4.1fId %3.1fWa %3.1fNi %3.1fKe %3.1fHi %3.1fSi %3.1fSt %3.1fGu %3.1fGN", (float)deltaCpu.user*100/sumCpu, (float)deltaCpu.system*100/sumCpu, (float)deltaCpu.idle*100/sumCpu, (float)deltaCpu.wait*100/sumCpu, (float)deltaCpu.nice*100/sumCpu, (float)deltaCpu.kernel*100/sumCpu, (float)deltaCpu.intr*100/sumCpu, (float)deltaCpu.softintr*100/sumCpu, (float)deltaCpu.steal*100/sumCpu, (float)deltaCpu.guest*100/sumCpu, (float)deltaCpu.guestnice*100/sumCpu); line++; } if (has_mem) { printw("\nMem: %10s Total %10s Used %10s Free %10s Buffer", format_humanmem(b1, sizeof b1, mem.totalReal), format_humanmem(b2, sizeof b2, mem.totalReal-mem.availReal), format_humanmem(b3, sizeof b3, mem.availReal), format_humanmem(b4, sizeof b4, mem.buffer)); line++; printw("\nSwap: %10s Total %10s Used %10s Free %10s Cached", format_humanmem(b1, sizeof b1, mem.totalSwap), format_humanmem(b2, sizeof b2, mem.totalSwap-mem.availSwap), format_humanmem(b3, sizeof b3, mem.availSwap), format_humanmem(b4, sizeof b4, mem.cached)); line++; } printw("\n%7s %4s %6s %10s %11s %5s %-10s", "Index", "Type", "Status", "Memory", "Total CPU", "%CPU", "Command"); line++; ninx = 0; while (line < LINES && ninx < ncount) { struct hrSWRunTable *proc = nproc+ninx; const char *hr_status, *hr_type; ninx++; if (proc->hrSWRunPerfCPUInc == 0 && !show_idle) continue; if (proc->hrSWRunType != 4 && !show_os) continue; line++; switch (proc->hrSWRunType) { case 1: hr_type = "Unkn"; break; case 2: hr_type = "Os"; break; case 3: hr_type = "Drvr"; break; case 4: hr_type = "Appl"; break; default: hr_type = "?"; break; } switch (proc->hrSWRunStatus) { case 1: hr_status = "Run"; break; case 2: hr_status = "Wait"; break; case 3: hr_status = "Event"; break; case 4: hr_status = "Inval"; break; default: hr_status = "?"; break; } printw("\n%7lu %4s %6s %10s %11s %5.1f %s %s", proc->hrSWRunIndex, hr_type, hr_status, format_humanmem(b1, sizeof b1, proc->hrSWRunPerfMem), format_sec(b2,sizeof b2, proc->hrSWRunPerfCPU), (float)proc->hrSWRunPerfCPUInc/5, command_path && proc->hrSWRunPath[0] ? proc->hrSWRunPath : proc->hrSWRunName, command_args ? proc->hrSWRunParameters : ""); } refresh(); qsort(nproc, ncount, sizeof(nproc[0]), pidcomp); free_perf(oproc, ocount); oproc = nproc; ocount = ncount; } endwin(); snmp_close(ss); SOCK_CLEANUP; return 0; }
int main(int argc, char *argv[]) { netsnmp_session session, *ss; netsnmp_pdu *pdu; netsnmp_pdu *response; int arg; oid base[MAX_OID_LEN]; size_t base_length; int status; netsnmp_variable_list *saved = NULL, *vlp = saved, *vlp2; int count = 0; /* * get the common command line arguments */ switch (arg = snmp_parse_args(argc, argv, &session, "C:", optProc)) { case NETSNMP_PARSE_ARGS_ERROR: exit(1); case NETSNMP_PARSE_ARGS_SUCCESS_EXIT: exit(0); case NETSNMP_PARSE_ARGS_ERROR_USAGE: usage(); exit(1); default: break; } if (arg != argc) { fprintf(stderr, "snmpdf: extra argument: %s\n", argv[arg]); exit(1); } SOCK_STARTUP; /* * Open an SNMP session. */ ss = snmp_open(&session); if (ss == NULL) { /* * diagnose snmp_open errors with the input netsnmp_session pointer */ snmp_sess_perror("snmpdf", &session); SOCK_CLEANUP; exit(1); } printf("%-18s %15s %15s %15s %5s\n", "Description", "size (kB)", "Used", "Available", "Used%"); if (ucd_mib == 0) { /* * * Begin by finding all the storage pieces that are of * * type hrStorageFixedDisk, which is a standard disk. */ pdu = snmp_pdu_create(SNMP_MSG_GETNEXT); base_length = add(pdu, "HOST-RESOURCES-MIB:hrStorageIndex", NULL, 0); memcpy(base, pdu->variables->name, base_length * sizeof(oid)); vlp = collect(ss, pdu, base, base_length); while (vlp) { size_t units; unsigned long hssize, hsused; char descr[SPRINT_MAX_LEN]; int len; pdu = snmp_pdu_create(SNMP_MSG_GET); add(pdu, "HOST-RESOURCES-MIB:hrStorageDescr", &(vlp->name[base_length]), vlp->name_length - base_length); add(pdu, "HOST-RESOURCES-MIB:hrStorageAllocationUnits", &(vlp->name[base_length]), vlp->name_length - base_length); add(pdu, "HOST-RESOURCES-MIB:hrStorageSize", &(vlp->name[base_length]), vlp->name_length - base_length); add(pdu, "HOST-RESOURCES-MIB:hrStorageUsed", &(vlp->name[base_length]), vlp->name_length - base_length); status = snmp_synch_response(ss, pdu, &response); if (status != STAT_SUCCESS || !response) { snmp_sess_perror("snmpdf", ss); exit(1); } vlp2 = response->variables; len = vlp2->val_len; if (len >= SPRINT_MAX_LEN) len = SPRINT_MAX_LEN-1; memcpy(descr, vlp2->val.string, len); descr[len] = '\0'; vlp2 = vlp2->next_variable; units = vlp2->val.integer ? *(vlp2->val.integer) : 0; vlp2 = vlp2->next_variable; hssize = vlp2->val.integer ? *(vlp2->val.integer) : 0; vlp2 = vlp2->next_variable; hsused = vlp2->val.integer ? *(vlp2->val.integer) : 0; printf("%-18s %15lu %15lu %15lu %4lu%%\n", descr, units ? convert_units(hssize, units, 1024) : hssize, units ? convert_units(hsused, units, 1024) : hsused, units ? convert_units(hssize-hsused, units, 1024) : hssize - hsused, hssize ? convert_units(hsused, 100, hssize) : hsused); vlp = vlp->next_variable; snmp_free_pdu(response); count++; } } if (count == 0) { size_t units = 0; /* * the host resources mib must not be supported. Lets try the * UCD-SNMP-MIB and its dskTable */ pdu = snmp_pdu_create(SNMP_MSG_GETNEXT); base_length = add(pdu, "UCD-SNMP-MIB:dskIndex", NULL, 0); memcpy(base, pdu->variables->name, base_length * sizeof(oid)); vlp = collect(ss, pdu, base, base_length); while (vlp) { unsigned long hssize, hsused; char descr[SPRINT_MAX_LEN]; pdu = snmp_pdu_create(SNMP_MSG_GET); add(pdu, "UCD-SNMP-MIB:dskPath", &(vlp->name[base_length]), vlp->name_length - base_length); add(pdu, "UCD-SNMP-MIB:dskTotal", &(vlp->name[base_length]), vlp->name_length - base_length); add(pdu, "UCD-SNMP-MIB:dskUsed", &(vlp->name[base_length]), vlp->name_length - base_length); status = snmp_synch_response(ss, pdu, &response); if (status != STAT_SUCCESS || !response) { snmp_sess_perror("snmpdf", ss); exit(1); } vlp2 = response->variables; memcpy(descr, vlp2->val.string, vlp2->val_len); descr[vlp2->val_len] = '\0'; vlp2 = vlp2->next_variable; hssize = *(vlp2->val.integer); vlp2 = vlp2->next_variable; hsused = *(vlp2->val.integer); printf("%-18s %15lu %15lu %15lu %4lu%%\n", descr, units ? convert_units(hssize, units, 1024) : hssize, units ? convert_units(hsused, units, 1024) : hsused, units ? convert_units(hssize-hsused, units, 1024) : hssize - hsused, hssize ? convert_units(hsused, 100, hssize) : hsused); vlp = vlp->next_variable; snmp_free_pdu(response); count++; } } if (count == 0) { fprintf(stderr, "Failed to locate any partitions.\n"); exit(1); } snmp_close(ss); SOCK_CLEANUP; return 0; } /* end main() */