I’m running into an issue when I try to call WNetAddConnection2 to a machine in which I already have a session to. This is expected, as you can only connect to a network resource with only one set of credentials. What I’m trying to do is catch this condition and automatically call WNetCancelConnection2 to disconnect all existing connections and then retry the WNetAddConnection2 call. When I run the below code I get these log messages:
DEBUG - WNetAddConnection2 returned 1219
DEBUG - Multiple credentials detected, disconnecting all current sessions
DEBUG - WNetCancelConnection2 returned 0
DEBUG - WNetAddConnection2 returned 1219
If I set dwFlags to CONNECT_UPDATE_PROFILE in WNetCancelConnection I get these log messages:
DEBUG - WNetAddConnection2 returned 1219
DEBUG - Multiple credentials detected, disconnecting all current sessions
DEBUG - WNetCancelConnection2 returned 2250
DEBUG - WNetAddConnection2 returned 1219
Here is my source, all help is appreciated!
networkName = @"\192.168.1.1";
var netResource = new NetResource()
{
Scope = ResourceScope.GlobalNetwork,
ResourceType = ResourceType.Disk,
DisplayType = ResourceDisplaytype.Share,
RemoteName = networkName
};
int result = WNetAddConnection2(netResource, credentials.Password, credentials.UserName, 0);
log.Debug("WNetAddConnection2 returned " + result);
if (result == 1219)
{
log.Debug("Multiple credentials detected, disconnecting all current sessions");
result = WNetCancelConnection2(networkName, 0, true);
log.Debug("WNetCancelConnection2 returned " + result);
result = WNetAddConnection2(netResource, credentials.Password, credentials.UserName, 0);
log.Debug("WNetAddConnection2 returned " + result);
}
|
|
|
Соблюдайте общие правила форума
Пожалуйста, выделяйте текст программы тегом [сode=pas] … [/сode]. Для этого используйте кнопку [code=pas] в форме ответа или комбобокс, если нужно вставить код на языке, отличном от Дельфи/Паскаля.
Указывайте точные версии Delphi и используемых сетевых библиотек.
Не приветствуется поднятие старых тем. Если ваш вопрос перекликается со старой темой, то для вопроса лучше создать новую тему, а старую указать в первом сообщении с описанием взаимосвязи.
Внимание:
попытки открытия обсуждений реализации вредоносного ПО, включая различные интерпретации спам-ботов, наказывается предупреждением на 30 дней.
Повторная попытка — 60 дней. Последующие попытки бан.
Мат в разделе — бан на три месяца…
Полезные ссылки:
MSDN Library FAQ раздела Поиск по разделу Как правильно задавать вопросы
Выразить свое отношение к модераторам раздела можно здесь: Krid, Rouse_
Использование функции WNetAddConnection2
, Не удается подключить сетевой ресурс
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
Не удается подключить сетевой диск С на рабочей станции Когда я делаю так :
begin WNetConnectionDialog(Handle,RESOURCETYPE_DISK) end; Тогда все получается. Только такой вариант меня не устраивает А если делаю вот так :
begin NetResource.dwType := RESOURCETYPE_DISK; NetResource.lpLocalName := ‘Z:’; NetResource.lpRemoteName := ‘\10.57.112.5c’; NetResource.lpProvider := »; IF (WNetAddConnection2(NetResource,»,»,CONNECT_UPDATE_PROFILE))<> NO_ERROR then showmessage(IntToStr(GetLastError())); end; Функция GetLastError возвращает код ошибки 53 — Сетевой путь не найден ! Сообщение отредактировано: Oleg2004 — 17.11.09, 13:42 |
Gesha |
|
Извините меня, программисты, если я кого-то своим вопросом обидел. Я прочитал раздел «Как правильно задавать вопросы». Дело в том, что мне действительно очень нужно разобраться почему у меня не работает функция WNetAddConnection2().Поверте, я не собираюсь у кого-то выпытывать ума и сопоставлять примеры из учебников. |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- Delphi: Сетевое программирование
- Следующая тема
[ Script execution time: 0,0370 ] [ 16 queries used ] [ Generated: 4.06.23, 13:17 GMT ]
WEC uses the following process to read remote event logs.
- Connect to the remote computer using the provided username and password
- Error messages will have «WNetAddConnection2 failed with error: <error>»
- Connect to the remote registry
- Error messages will have «eventLogRegistryKeyCheck: <error>»
- Note: The Remote Registry service must be running on the remote computer.
- Check if the event log is present by opening the event log’s registry key.
- Error messages will have «eventLogRegistryKeyCheck: <error>»
- Open the Event log
- Error messages will have «OpenEventLog: <error>»
- Read the Event Log entries.
Common scenarios with the error message.
Unable to connect to the remote computer due to network issue:
-
ERROR [Time] [Sensor] [Machine]:[Event Log] Source:Application Error in EventLogReader initialization ex=com.symantec.cas.ucf.sensors.OpenDeviceException: ERROR_CODE[1203]. WNetAddConnection2 failed with error: No network provider accepted the given network path.
This error is usually caused by an networking/connectivity problem between the Collector machine and machine and the log host (target) machine. To resolve this problem, resolve the underlying network issue and the collector should start working normally.
Unable to connect to the remote computer due to incorrect credentials:
-
ERROR [Time] [Sensor] [Machine]:[Event Log] Source:Application Error in EventLogReader initialization ex=com.symantec.cas.ucf.sensors.OpenDeviceException: ERROR_CODE[1326]. WNetAddConnection2 failed with error: Logon failure: unknown user name or bad password.
or
ERROR_CODE[1312]. WNetAddConnection2 failed with error: A specified logon session does not exist. It may already have been terminated.
These errors are usually resolved by entering correct credentials into the sensor configuration.
Note: You may need to set the Monitored Host Account Name to
<Computer IP><username> or <Computer Name><username>
.
Note: If you continue to receive this error but you are confident the credentials are correct please contact support.
If the Remote Registry service is not running or is not accessible:
- The Event Log registry entry is not present.
Contact Microsoft support if you find the registry key is missing.
- The Event Log registry key is not readable due to a permission issue.
Adjust permissions for the user that you have configured in your sensor settings to allow them access to the event log registry key. For assistance with this permissions issue please contact Microsoft support.
- If you are running Microsoft Windows Server 2003 Service Pack 1 you may need to upgrade to Service Pack 2. Please see Microsoft KB article 906570:
A custom program that uses the RegConnectRegistry function can no longer access the registry of a remote computer http://support.microsoft.com/kb/906570
- The WEC Sensor configuration has listed the Host name incorrectly.
Try listing a simple hostname instead of FQDN, or vice versa. The correct entry varies depending on your DNS or Hosts file entries.
- The user is not in the local administrator group.
Unless the target machine is a Domain Controller, the user that you enter into the sensor configuration must be in the local administrators group even if the user is a domain admin. For assistance adding a user to the Local Administrators group please contact Microsoft Support.
- Be sure the Remote Registry service is running on the remote computer.
- ERROR [Time] [Sensor] [Machine]:[Event Log] Source:Application Error in EventLogReader initialization ex=com.symantec.cas.ucf.sensors.OpenDeviceException: ERROR_CODE[53]. eventLogRegistryKeyCheck failed with error: The network path was not found.
- WARN [Time] [Sensor] [Machine]:[Event Log] Source:System Source:System Reopenning eventlog failed with exception: ERROR_CODE[1726]. OpenEventLog failed with error: The remote procedure call failed.
Note: The event log registry key is: HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesEventlog<Event log name>
This error can be caused by the following problems:
ERROR [Time] [Sensor] [Machine]:[Event Log] Source:EventLogNotPresent Error in EventLogReader initialization ex=com.symantec.cas.ucf.sensors.OpenDeviceException: ERROR_CODE[997]. eventLogRegistryKeyCheck failed with error: Overlapped I/O operation is in progress.
The registry is corrupt or damaged:
- WARN [Time] [Sensor] [Machine]:[Event Log] Source:Security Reader failed to open device with error: ERROR_CODE[1500]. EventLog.read
- Click on the start button and select Administrative Tools.
- Next, click on Event Viewer
- Right click on Security log and select Clear All Events.
- When asked to save your security log, click on Yes. Fill in a name for the folder, then click Save.
- The log is now removed from the affected system.
- Restart the agent and observe the event flow.
failed with error: El archivo de registro de sucesos está dañado. Trying to reopen…
The collector is trying to pull down the events, however the event log is damaged or corrupted and needs to be deleted. Follow these steps on how to delete the corrupted log file.
In this example we will use the security log.
If the user has permissions to connect remotely, but does not have permissions to other services
User does not have permission’s to the registry:
Application Reader can not access registry on target box. Make sure user [Username] has permission’s to access registry on [Computer Name].
User does not have permission’s to resources (can be caused by trust relationship on domain, or the user is not a member of the domain):
Application Reader failed to login into target box. Make sure sensor configuration has correct credentials and user [Username] has permission’s to access [Computer Name].
HI Iam Using WnetConnection2 Api in C#.net and when compiling this its giving Invalid Address ,But its working in VB.net,Iam passing ip address
This is the code Below
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace AutoBackupTool
{
public struct NETRESOURCE1
{
long dwScope;
public long dwType;
long dwDisplayType;
long dwUsage;
public string lpLocalName;
public string lpRemoteName;
public string lpComment;
string lpProvider;
}
public partial class Form2 : Form
{
public const long RESOURCETYPE_DISK = 1;
[DllImport(«mpr.dll», EntryPoint = «WNetAddConnection2», CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int WNetAddConnection2(ref NETRESOURCE1 lpNetResource, string lpPassword, string lpUserName, int dwFlags);
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string UNCPath = string.Empty;
string DriveLetter = string.Empty;
MapDrive(DriveLetter, UNCPath);
}
public void MapDrive(string DriveLetter, string UNCPath)
{
try
{
NETRESOURCE1 nr1 = new NETRESOURCE1();
//string x1 = «\» + «\» + Sch_SystemName + «\d$»;
string UNCPath1 =«\\172.27.48.156\d$»;
nr1.lpLocalName = «c:»;
nr1.lpRemoteName = UNCPath1;
//nr.lpLocalName = DriveLetter & «:»
string strUsername = «Administrator»;
//(add parameters to pass this if necessary)
string strPassword = «paone»;
//(add parameters to pass this if necessary)
nr1.dwType = RESOURCETYPE_DISK;
//}
int result1 = 0;
//result = WNetAddConnection2(ref nr, strPassword, strUsername, 0);
result1 = WNetAddConnection2(ref nr1, strPassword, strUsername, 0);
if (result1 == 0)
{
MessageBox.Show(«System Connetced Successfully»);
}
else
{
//MessageBox.Show(«System Not Connetced Successfully»);
}
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}
}
//}
}
PLZ Help Me
Thanks in Advance
Sudhir Babu
|
|