libnm和C:如何获取已保存的无线网络的密码?

问题描述

我正在尝试使用libnm 1.12.10获取保存在Ubuntu 20.02上的无线网络的密码。我想我应该对NMSecretAgentOld进行一些操作,但是我不知道到底是什么以及如何操作。我也没有在互联网上找到任何例子。 这是我当前的测试代码

/*
* The example shows how to list connections.  Contrast this example with
* list-connections-gdbus.c,which is a bit lower level and talks directly to NM
* using GDBus.
*
* Compile with:
*   gcc -Wall test.cpp -o test `pkg-config --libs --cflags libnm`
*/

#include <glib.h>
#include <stdio.h>
#include <stdlib.h>

#include <NetworkManager.h>
#include <nm-secret-agent-old.h>

/* Print details of connection */
static void
show_connection (NMConnection *connection)
{
   printf("--- CONNECTION ---\n");
   NMSettingWireless* s_con;
   NMSettingWirelessSecurity* wifiSec;
   const char* interfce;
   interfce = nm_connection_get_interface_name(connection);
   s_con = nm_connection_get_setting_wireless(connection);
   if (s_con) {
       GBytes* ssidBytes = nm_setting_wireless_get_ssid(s_con);
       const char* ssid = nm_utils_ssid_to_utf8((guint8 *)g_bytes_get_data(ssidBytes,NULL),g_bytes_get_size(ssidBytes));
       printf("SSID: %s\nInterface: %s\n",ssid,interfce);
       wifiSec = nm_connection_get_setting_wireless_security(connection);
       if(wifiSec){
           const char* auth = nm_setting_wireless_security_get_auth_alg(wifiSec);
           const char* encrypt = nm_setting_wireless_security_get_key_mgmt(wifiSec);
           const char* psk = nm_setting_wireless_security_get_psk(wifiSec); //THIS RETURNS NULL! BUT THE WPA-PSK PASSWORD IS SET!
           printf("Auth: %s\nEncryption: %s\nPassword: %s\n",auth,encrypt,psk);
           nm_connection_dump(connection); //Also in debug dump no password field
       }
   }
}

int
main (int argc,char *argv[])
{
   NMClient *client;
   GError *error = NULL;
   const GPtrArray *connections;
   int i;

#if !GLIB_CHECK_VERSION (2,35,0)
   /* Initialize GType system */
   g_type_init ();
#endif
   if (!(client = nm_client_new (NULL,&error))) {
       g_message ("Error: Could not connect to NetworkManager: %s.",error->message);
       g_error_free (error);
       return EXIT_FAILURE;
   }

   if (!nm_client_get_nm_running (client)) {
       g_message ("Error: Can't obtain connections: NetworkManager is not running.");
       return EXIT_FAILURE;
   }
   /* Now the connections can be listed. */
   connections = nm_client_get_connections (client);

   printf ("Connections:\n===================\n");

   for (i = 0; i < connections->len; i++)
       show_connection ((NMConnection*) connections->pdata[i]);

   g_object_unref (client);

   return EXIT_SUCCESS;
}

这是程序输出中有趣的部分:Program output image

这是etc / NetworkManager / system_connections转储(在其中设置了psk字段):Wireless Network file dump image

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)