programma che spenga computer

Stato
Discussione chiusa ad ulteriori risposte.

kr1pn0$

Utente Silver
14 Ottobre 2008
69
5
0
70
ciao,
io in questo esercizio propongo di creare un programma che:
- spenga il pc(linux o windows o os)
- Abbia 2 timer (60 ,30 secondi)
- che sia un timer interno al programma e quindi no:
Esempio con win:
Codice:
shutdown -s -t 60
-e riavii il pc sempre con o senza timer
ecco il mio C Code
[attenzione è linkato con dev-cpp quindi non ditemi che mancano inclusioni]
[ot]
VERSIONE WINDOWS
Codice:
#include <stdio.h>
main(char **argv[]){
          int n=0;
          int t=0;
          system("title Shutdown By Kr1pn0$");
          system("color f0");
          printf("Decidi cosa fare:\n"
                 "\t\t1-Spegni il computer con timer di 1 un minuto\n"
                 "\t\t2-riavvia il computer con timer di 1 un minuto\n"
                 "\t\t3-Spegni il computer con timer di 30 secondi\n"
                 "\t\t4-riavvia il computer con timer di 30 secondi\n"
                 "\t\t5-Spegni il computer\n"
                 "\t\t6-riavvia\n"
                 "\n\n\n\t\t\t\t\tDesigned by kr1pn0$\n");
          scanf("%d",&n);
          if(n>6 || n<1){
                 printf("\n\n\nNon hai digitato un numero valido");
                 return 1;
          }
          if(n==1){
                   system("cls");
                   for(t=60;t>=0;t--){
                                      printf("TIMER AVVIATO\n\n");
                                      printf("Mancano %d secondi...",t);
                                      sleep(1000);
                                      system("cls");
                   }
                   system("shutdown -s");
          }
          if(n==2){
                   system("cls");
                   for(t=60;t>=0;t--){
                                      printf("TIMER AVVIATO\n\n");
                                      printf("Mancano %d secondi...",t);
                                      sleep(1000);
                                      system("cls");
                   }
                   system("shutdown -r");
          }
          if(n==3){
                   system("cls");
                   for(t=30;t>=0;t--){
                                      printf("TIMER AVVIATO\n\n");
                                      printf("Mancano %d secondi...",t);
                                      sleep(1000);
                                      system("cls");
                   }
                   system("shutdown -r");
          }
          if(n==4){
                   system("cls");
                   for(t=30;t>=0;t--){
                                      printf("TIMER AVVIATO\n\n");
                                      printf("Mancano %d secondi...",t);
                                      sleep(1000);
                                      system("cls");
                   }
                   system("shutdown -r");
          }
          if(n==5){
                   system("shutdown -s");
          }
          if(n==6){
                   system("shutdown -r");
          }
}
[/ot]
 
RE: spegnimento computer

in java:
Codice:
import java.io.*;
public class ShoutDownPC{
    public ShoutDownPC(){
        try{BufferedReader t=new BufferedReader(new InputStreamReader(System.in));
            Runtime r=Runtime.getRuntime();
            String[] s=new String[2];
            do{
                System.out.println("1\tSpegni tra 1 minuto");
                System.out.println("2\tRiavvia tra 1 minuto");
                System.out.println("3\tSpegni tra 30 secondi");
                System.out.println("4\tRiavvia tra 30 secondi");
                System.out.println("5\tSpegni il computer");
                System.out.println("6\tRiavvia il computer");
                System.out.println("Digita il numero:");
                int f=Integer.parseInt(t.readLine());
                if(f>=1 && f<=6){
                    switch(f){
                        case 1:System.out.println("Il computer si spegnerà tra 60 secondi");time(60);s[0]="shutdown";s[1]="-s";break;
                        case 2:System.out.println("Il computer si riavvierà tra 60 secondi");time(30);s[0]="shutdown";s[1]="-r";break;
                        case 3:System.out.println("Il computer si spegnerà tra 30 secondi");time(60);s[0]="shutdown";s[1]="-s";break;
                        case 4:System.out.println("Il computer si riavvierà tra 30 secondi");time(30);s[0]="shutdown";s[1]="-r";break;
                        case 5:System.out.println("Il computer sta per essere spento");s[0]="shutdown";s[1]="-s";break;
                        case 6:System.out.println("Il computer sta per essere riavviato");s[0]="shutdown";s[1]="-r";break;
                    }r.exec(s);break;
                } System.out.println("Inserire un numero valito!");
            }while(true);
        }catch(Exception e){System.out.println("ERRORE:"+e.getMessage());}
    }
    private void time(int v) throws java.lang.InterruptedException{
        Thread.sleep((v*1000));   
    }
}
Chi me lo prova su linux?:D
 
RE: spegnimento computer

scusate se son preciso, ma il titolo non è proprio corretto. Il codice riportato fin ora non esegue lo shutdown ma lancia un programma che esegue lo shutdown, pertanto penso sia ben diverso.

Preddy
 
RE: spegnimento computer

in effetti...
[ot]che pignolo st'alieno xD[/ot]
ma alla fine credo che sia richiesto il risultato di spegnere il pc,che lo fai richiamando altri programmi o lo fai calcolando il tempo di bastonate al pc credo sia uguale...
 
RE: spegnimento computer

kripnos comunque guardando il tuo codice ho notato che scrivi più volte i for...e credo sia proprio inutile...
 
RE: spegnimento computer

ok io propongo una vera soluzione in assembler
ecco una versione ridotta di codice ma perfettamente funzionate, setto i privilegi, spengo il sistema ed esco. il tutto in 3 righe di codice :D
Codice:
.486
.model flat,stdcall
include ntdll.inc
include kernel32.inc
includelib ntdll.lib
includelib kernel32.lib
.code
start: push esp
	invoke RtlAdjustPrivilege,19,2,0,esp
	invoke NtShutdownSystem,2
	jmp ExitProcess
end start

DOWNLOAD CODICE SORGENTE E BINARIO

posso scrivere la versione estesa di una 40ina di righe ma preferisco ottimizzare :)

Preddy
 
RE: spegnimento computer

MrDarkest ha detto:
la funzione NtShutdownSystem è di kernel32.dll preddy?
è nella ntdll

ShuraBozz ha detto:
Preddy che ne dici di postare una soluzione meno drastica???
Mi sono spaventato sai...:confused:

mi sono rotolato dalle risate :lol:
siccome so quanto rapido è lo spegnimento, mi sono immaginato te come ci sei restato :lol: :lol: :lol:

la NtShutdownSystem è una funzione molto potente non documentata. Solitamente usata nella programmazione a basso livello.

Preddy
 
RE: spegnimento computer

ShuraBozz ha detto:
non vale, lo volevo fare io in C...:(
fammi causa...:asd:
Adesso mi sto studiando il ruby,
dopo il C sarà tutto tuo...:D (Blacklight escluso:asd:)

@razor: I Lov3 For :asd:
@preddy: adesso provo a spegnere il pc chiudendo tutti i processi... secondo te va?
Comunque, sei il mio dio del assembly
@shurabozz: Anche a me fa pausa preddy quando invoca sti codici
 
Chi lo conosce può darmi il prototipo della funzione NtShutdownSystem per .NET? Ho cercato su google e su pinvoke.net ma niente.
 
[asm/linux]
Codice:
section .text
global _start
_start:
mov eax,37
mov ebx,-1
mov ecx,9
int 0x80

uppo solamente l'eseguibile ELF64. (non riesco a compilarlo in 32bit, ld ritorna errore :emba: )

edit: perchè, perchè, PERCHÈ non posso uppare dei tar.gz ? :evil:
 
avevo praticamente riscritto il codice dell' shut down, quando come un deficente mi son reso conto che stavo riscrivendo tutto quello che già c'era nel sistema, pertanto un bel colpo di canc e vi incollo il codice ottimizzato per un shutdown normale e non di cattiveria come sopra.
Codice:
;Normal ShutDown for NT system - By Predator
.486
.model  flat, stdcall
option  casemap:none

include     user32.inc
include     kernel32.inc
include     advapi32.inc
include     windows.inc
include 	ntdll.inc

includelib  kernel32.lib
includelib  user32.lib
includelib	ntdll.lib

.DATA

.CODE

START:push esp
    invoke RtlAdjustPrivilege,19,2,0,esp
    invoke  ExitWindowsEx, EWX_SHUTDOWN, 0 ;se scrivete EWX_REBOOT al posto di EWX_SHUTDOWN il sistema si riavvia invece di spegnersi
    invoke  ExitProcess,NULL
END START

DOWNLOAD SORGENTE E BINARIO

il sorgente non fa nessun controllo per verificare se siamo in un sistema NT based (cioè Win2000, XP, Vista, Server)
se vi interessa vi scrivo codice assembler per far capire senza l'utilizzo delle api se si è in un sistema NT e come settare i privilegi tutto senza API.

Preddy
 
MrDarkest ha detto:
Chi lo conosce può darmi il prototipo della funzione NtShutdownSystem per .NET? Ho cercato su google e su pinvoke.net ma niente.

in ogni caso devi settare i privilegi di amministrazione (che rottura sti token ;D) , questo codice dovrebbe fare al caso tuo:
VB. NET

QUESTO E' IL FORM1 CON INSERITI 2 TASTI
Codice:
Public Class Form1

    Public Sub AdjustToken()

        Const TOKEN_ADJUST_PRIVILEGES As Integer = &H20
        Const TOKEN_QUERY As Integer = &H8
        Const SE_PRIVILEGE_ENABLED As Integer = &H2

        Dim hdlProcessHandle As Integer
        Dim hdlTokenHandle As Integer
        Dim tmpLuid As LUID
        Dim tkp As TOKEN_PRIVILEGES
        Dim tkpNewButIgnored As TOKEN_PRIVILEGES
        Dim lBufferNeeded As Integer

        SetLastError(0)

        hdlProcessHandle = GetCurrentProcess()

        If GetLastError <> 0 Then
            MsgBox("GetCurrentProcess Errore:" & GetLastError)
        End If

        OpenProcessToken(hdlProcessHandle, TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY, hdlTokenHandle)

        If GetLastError <> 0 Then
            MsgBox("OpenProcessToken Errore:" & GetLastError)
        End If

        'LookupPrivilegeValue("", "SeShutdownPrivilege", tmpLuid)

        'If GetLastError <> 0 Then
        '    MsgBox("LookupPrivilegeValue Errore:" & GetLastError)
        'End If

        tkp.PrivilegeCount = 1
        tkp.TheLuid = tmpLuid
        tkp.Attributes = SE_PRIVILEGE_ENABLED

        AdjustTokenPrivileges(hdlTokenHandle, False, tkp, Len(tkpNewButIgnored), tkpNewButIgnored, lBufferNeeded)

        If GetLastError <> 0 Then
            MsgBox("AdjustTokenPrivileges Errore:" & GetLastError)
        End If

    End Sub

    Private Sub Form1_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
        Dim lngVersion As Integer
        'versione di windows
        lngVersion = GetVersion()
        'verifica se sei in un sistema NT
        If ((lngVersion And &H80000000) = 0) Then
            glngWhichWindows32 = mlngWindowsNT
        Else
            glngWhichWindows32 = mlngWindows95
        End If
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        If glngWhichWindows32 = mlngWindowsNT Then AdjustToken()
        'Reboot
        ExitWindowsEx(EWX_REBOOT Or EWX_FORCE, &HFFFF)
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If glngWhichWindows32 = mlngWindowsNT Then AdjustToken()
        'shutdown
        ExitWindowsEx(EWX_SHUTDOWN Or EWX_FORCE, &HFFFF)
    End Sub
End Class

QUESTO E' UN MODULO
Codice:
Module Module1

    Public glngWhichWindows32 As Integer
    Public Declare Sub SetLastError Lib "kernel32" (ByVal dwErrCode As Integer)
    Public Declare Function ExitWindowsEx Lib "user32" (ByVal dwOptions As Integer, ByVal dwReserved As Integer) As Integer
    Public Declare Function GetVersion Lib "kernel32" () As Integer
    Public Declare Function GetLastError Lib "kernel32" () As Integer
    Public Declare Function GetCurrentProcess Lib "kernel32" () As Integer
    Public Declare Function OpenProcessToken Lib "advapi32" (ByVal ProcessHandle As Integer, ByVal DesiredAccess As Integer, ByRef TokenHandle As Integer) As Integer
    'Public Declare Function LookupPrivilegeValue Lib "advapi32" Alias "LookupPrivilegeValueA" (ByVal lpSystemName As String, ByVal lpName As String, ByRef lpLuid As LUID) As Integer
    Public Declare Function AdjustTokenPrivileges Lib "advapi32" (ByVal TokenHandle As Integer, ByVal DisableAllPrivileges As Integer, ByRef NewState As TOKEN_PRIVILEGES, ByVal BufferLength As Integer, ByRef PreviousState As TOKEN_PRIVILEGES, ByRef ReturnLength As Integer) As Integer
    Public Const EWX_LogOff As Integer = 0
    Public Const EWX_SHUTDOWN As Integer = 1
    Public Const EWX_REBOOT As Integer = 2
    Public Const EWX_FORCE As Integer = 4
    Public Const EWX_POWEROFF As Integer = 8
    Public Const mlngWindows95 As Short = 0
    Public Const mlngWindowsNT As Short = 1
    Public Structure LUID
        Dim UsedPart As Integer
        Dim IgnoredForNowHigh32BitPart As Integer
    End Structure

    Public Structure LUID_AND_ATTRIBUTES
        Dim TheLuid As LUID
        Dim Attributes As Integer
    End Structure

    Public Structure TOKEN_PRIVILEGES
        Dim PrivilegeCount As Integer
        Dim TheLuid As LUID
        Dim Attributes As Integer
    End Structure
End Module

ho commentato il lookup dei privilegi perchè non so ancora come si utilizzano in .Net, ho provato ma non ho avuto fortuna in poco tempo.

Preddy
 
Stato
Discussione chiusa ad ulteriori risposte.